在 ASP.NET Core 应用程序中将 HTTPS 站点重定向到非 www

Posted

技术标签:

【中文标题】在 ASP.NET Core 应用程序中将 HTTPS 站点重定向到非 www【英文标题】:Redirecting HTTPS site to non-www in ASP.NET Core application 【发布时间】:2018-08-07 23:49:17 【问题描述】:

我正在设置我的第一个 ASP.NET 核心应用程序。此应用程序在 HTTPS 上运行。目前,我有两个响应的域:domain.dkwww.domain.dk,我想将 301 重定向到 wwwnon www

我在 Google 上搜索了很多,最后添加了以下课程:

public class NonWwwRule : IRule

    public void ApplyRule(RewriteContext context)
    
        var req = context.HttpContext.Request;
        var currentHost = req.Host;
        if (currentHost.Host.StartsWith("www."))
        
            var newHost = new HostString(currentHost.Host.Substring(4), currentHost.Port ?? 80);
            var newUrl = new StringBuilder().Append("https://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
            context.HttpContext.Response.Redirect(newUrl.ToString());
            context.Result = RuleResult.EndResponse;
        
    

然后我将其添加到 Startup.cs 中的 Configure 方法中:

var options = new RewriteOptions();
options.Rules.Add(new NonWwwRule());
app.UseRewriter(options);

但是,我的网站仍然没有对此作出回应,www 和没有工作。

编辑:

我添加了日志记录。在我的ApplyRule 中,我发送了一些登录信息:

    public void ApplyRule(RewriteContext context)
    
        _logger.LogInformation("ApplyRule added");

        var req = context.HttpContext.Request;
        var currentHost = req.Host;

        _logger.LogInformation("Currenthost: " + currentHost.Host + " & URL: " + req.Path);

        if (currentHost.Host.StartsWith("www."))
        

            _logger.LogInformation("currentHost.Host.StartsWith");

            var newHost = new HostString(currentHost.Host.Substring(4), currentHost.Port ?? 443);
            var newUrl = new StringBuilder().Append("https://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
            _logger.LogInformation("newURL: " + newUrl);
            context.HttpContext.Response.Redirect(newUrl.ToString());
            _logger.LogInformation("response added: " + newUrl.ToString());
            context.Result = RuleResult.EndResponse;
            _logger.LogInformation("EndResponse added");
        
    

阅读我的日志,我得到的印象是它只被 JS 文件调用,而不是主请求。

2018-03-05 14:44:33.380 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/Content/styles/styles.css?v=RAlju8RYSVrnTxqDUl4Jj9OkakB2USJn8Hg8TkcZ2AY  
2018-03-05 14:44:33.383 +00:00 [Information] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Sending file. Request path: '/Content/styles/styles.css'. Physical path: 'D:\home\site\wwwroot\wwwroot\Content\styles\styles.css'
2018-03-05 14:44:33.383 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 2.8044ms 200 text/css
2018-03-05 14:44:33.638 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/Content/images/common/logo-dark.png  
2018-03-05 14:44:33.640 +00:00 [Information] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Sending file. Request path: '/Content/images/common/logo-dark.png'. Physical path: 'D:\home\site\wwwroot\wwwroot\Content\images\common\logo-dark.png'
2018-03-05 14:44:33.640 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 2.1224ms 200 image/png
2018-03-05 14:44:33.886 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/js/site.min.js  
2018-03-05 14:44:33.887 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 0.6345ms 302 
2018-03-05 14:44:34.019 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/Content/images/icons/result.svg  
2018-03-05 14:44:34.021 +00:00 [Information] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Sending file. Request path: '/Content/images/icons/result.svg'. Physical path: 'D:\home\site\wwwroot\wwwroot\Content\images\icons\result.svg'
2018-03-05 14:44:34.023 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 4.6392ms 200 image/svg+xml
2018-03-05 14:44:34.175 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/Content/images/icons/customerfocused.svg  
2018-03-05 14:44:34.175 +00:00 [Information] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Sending file. Request path: '/Content/images/icons/customerfocused.svg'. Physical path: 'D:\home\site\wwwroot\wwwroot\Content\images\icons\customerfocused.svg'
2018-03-05 14:44:34.176 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 0.9026ms 200 image/svg+xml
2018-03-05 14:44:34.180 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/Content/images/icons/responsible.svg  
2018-03-05 14:44:34.184 +00:00 [Information] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Sending file. Request path: '/Content/images/icons/responsible.svg'. Physical path: 'D:\home\site\wwwroot\wwwroot\Content\images\icons\responsible.svg'
2018-03-05 14:44:34.185 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 4.8705ms 200 image/svg+xml
2018-03-05 14:44:34.186 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://likvido.dk/js/site.min.js  
2018-03-05 14:44:34.186 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 0.527ms 404 
2018-03-05 14:44:34.265 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/Content/images/icons/professional.svg  
2018-03-05 14:44:34.265 +00:00 [Information] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Sending file. Request path: '/Content/images/icons/professional.svg'. Physical path: 'D:\home\site\wwwroot\wwwroot\Content\images\icons\professional.svg'
2018-03-05 14:44:34.265 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 0.855ms 200 image/svg+xml
2018-03-05 14:44:33.887 +00:00 [Information] Likvido.Website.Main.Startup: ApplyRule added
2018-03-05 14:44:33.887 +00:00 [Information] Likvido.Website.Main.Startup: Currenthost: www.likvido.dk & URL: /js/site.min.js
2018-03-05 14:44:33.887 +00:00 [Information] Likvido.Website.Main.Startup: currentHost.Host.StartsWith
2018-03-05 14:44:33.887 +00:00 [Information] Likvido.Website.Main.Startup: newURL: https://likvido.dk:443/js/site.min.js
2018-03-05 14:44:33.887 +00:00 [Information] Likvido.Website.Main.Startup: response added: https://likvido.dk:443/js/site.min.js
2018-03-05 14:44:33.887 +00:00 [Information] Likvido.Website.Main.Startup: EndResponse added
2018-03-05 14:44:34.186 +00:00 [Information] Likvido.Website.Main.Startup: ApplyRule added
2018-03-05 14:44:34.186 +00:00 [Information] Likvido.Website.Main.Startup: Currenthost: likvido.dk & URL: /js/site.min.js
2018-03-05 14:44:34.611 +00:00 [Information] Likvido.Website.Main.Startup: ApplyRule added
2018-03-05 14:44:34.611 +00:00 [Information] Likvido.Website.Main.Startup: Currenthost: www.likvido.dk & URL: /js/site.min.js
2018-03-05 14:44:34.611 +00:00 [Information] Likvido.Website.Main.Startup: currentHost.Host.StartsWith
2018-03-05 14:44:34.611 +00:00 [Information] Likvido.Website.Main.Startup: newURL: https://likvido.dk:443/js/site.min.js
2018-03-05 14:44:34.611 +00:00 [Information] Likvido.Website.Main.Startup: response added: https://likvido.dk:443/js/site.min.js
2018-03-05 14:44:34.611 +00:00 [Information] Likvido.Website.Main.Startup: EndResponse added
2018-03-05 14:44:34.714 +00:00 [Information] Likvido.Website.Main.Startup: ApplyRule added
2018-03-05 14:44:34.714 +00:00 [Information] Likvido.Website.Main.Startup: Currenthost: likvido.dk & URL: /js/site.min.js
2018-03-05 14:44:34.478 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/  
2018-03-05 14:44:34.478 +00:00 [Information] Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Executing action method Likvido.Website.Main.Controllers.HomeController.Index (Likvido.Website.Main) with arguments ((null)) - ModelState is Valid
2018-03-05 14:44:34.478 +00:00 [Information] Likvido.Website.Main.Controllers.HomeController: TEST INDEX LOGGER
2018-03-05 14:44:34.479 +00:00 [Information] Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor: Executing ViewResult, running view at path /Views/Home/Index.cshtml.
2018-03-05 14:44:34.479 +00:00 [Information] Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Executed action Likvido.Website.Main.Controllers.HomeController.Index (Likvido.Website.Main) in 0.9628ms
2018-03-05 14:44:34.481 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 2.4825ms 200 text/html; charset=utf-8
2018-03-05 14:44:34.484 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/Content/images/pages/bg-image-2.jpg  
2018-03-05 14:44:34.485 +00:00 [Information] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Sending file. Request path: '/Content/images/pages/bg-image-2.jpg'. Physical path: 'D:\home\site\wwwroot\wwwroot\Content\images\pages\bg-image-2.jpg'
2018-03-05 14:44:34.486 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/Content/images/icons/phone-icon-3.svg  
2018-03-05 14:44:34.487 +00:00 [Information] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Sending file. Request path: '/Content/images/icons/phone-icon-3.svg'. Physical path: 'D:\home\site\wwwroot\wwwroot\Content\images\icons\phone-icon-3.svg'
2018-03-05 14:44:34.487 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 0.9784ms 200 image/svg+xml
2018-03-05 14:44:34.500 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 16.1968ms 200 image/jpeg
2018-03-05 14:44:34.610 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://www.likvido.dk/js/site.min.js  
2018-03-05 14:44:34.611 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 1.3489ms 302 
2018-03-05 14:44:34.713 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting HTTP/1.1 GET http://likvido.dk/js/site.min.js  
2018-03-05 14:44:34.714 +00:00 [Information] Microsoft.AspNetCore.Hosting.Internal.WebHost: Request finished in 0.573ms 404 

【问题讨论】:

我有点困惑,当您向主机 www.* 发出请求时,您的浏览器是否会重定向,或者如果它重定向,它是否无法建立连接。我试过你的代码,它工作正常,www* 请求被重定向到非 www @UmarKarimabadi 感谢您的提问,这样就很清楚了。您可以在 likvido.dk 和 likvido.dk 看到作品。它根本没有做任何事情。就好像代码从未运行过:-) 这真的很奇怪,app.useRewriter 应该是第一个添加到你的 configure 方法中的东西。我在您的代码中看到的唯一错误是 currentHost.Port ? 80. https的端口当然是443。您将不得不添加一些日志记录以查看该重写器是否一开始就被命中 这应该可以正常工作(我刚刚测试过)。 @UmarKarimabadi 对港口提出了一个很好的观点。 @UmarKarimabadi - 我更新了一些日志并更新了帖子。同样的问题。但是,我不明白 - 我的 ApplyRule 似乎只为 JS 文件调用。有什么想法吗? 【参考方案1】:

从日志看,你的中间件好像弄错了

应该是

public void ConfigureServices(IServiceCollection services)
        
            services.AddMvc();
        

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        
            if (env.IsDevelopment())
            
                app.UseDeveloperExceptionPage();
            
            var options = new RewriteOptions();
            options.Rules.Add(new NonWwwRule());
            app.UseRewriter(options);
            app.UseStaticFiles();

            app.UseMvc();
        

应该先重写,再静态,再MVC

【讨论】:

是的!那行得通!干得好 :) 我将在 23 小时内奖励赏金(*** 强制延迟)。谢谢!【参考方案2】:

对于所有疯狂到在 F# 中做到这一点的人:

open Microsoft.AspNetCore.Http

type NonWwwRule () =
    interface IRule with
        member __.ApplyRule context =
            let request = context.HttpContext.Request
            let host = request.Host

            if host.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase) then
                let nonWwwPort = if host.Port.HasValue then host.Port.Value else 443
                let nonWwwHost = HostString(host.Host.Substring 4, nonWwwPort)
                let nonWwwPath = 
                    (sprintf "https://%s%s%s%s" 
                        nonWwwHost.Value
                        request.PathBase.Value 
                        request.Path.Value 
                        request.QueryString.Value)

                context.HttpContext.Response.Redirect nonWwwPath
                context.HttpContext.Response.StatusCode <- 301

                context.Result <- RuleResult.EndResponse
let options = RewriteOptions()
options.Rules.Add(NonWwwRule())
app.UseRewriter options |> ignore

【讨论】:

以上是关于在 ASP.NET Core 应用程序中将 HTTPS 站点重定向到非 www的主要内容,如果未能解决你的问题,请参考以下文章

防止 AddRedirectToWwwPermanent() 在 ASP.NET Core 2.1 中将“www”添加到 *.azurewebsites.net 的前面

如何在 ASP.NET CORE 5.0 MVC 中将登录设置为默认路由

在 ASP.NET Core 中将 RTSP 流从 IP 摄像机转发到浏览器

在 ASP.net Core 中将对象转换为 Json

在 ASP.NET Core 中将 html 导出为 pdf

Google Chart和Chart.Js,在Asp .NET Core 2.2中将脚本端发送C#变量