ASP.NET Core 1.1 Url重写 - www到非www

时间:2016-12-18 04:21:22

标签: url-rewriting asp.net-core asp.net-core-mvc

这是我使用ASP.NET Core 1.1 Url重写中间件从www重定向的核心。到非www:

var options = new RewriteOptions()
    .AddRedirect("^(www\\.)(.*)$", "$2");
app.UseRewriter(options);

由于某种原因,它不起作用。我知道正则表达式是正确的。这里有什么问题?

这是完整的配置功能:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseRequestLocalization(new RequestLocalizationOptions() { DefaultRequestCulture = new RequestCulture("ru-ru") });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            // URL Rewriting
            var options = new RewriteOptions()
                //.AddRedirect(@"^(https?:\/\/)(www\.)(.*)$", "$1$3");
                .AddRedirect("^(www\\.)(.*)$", "$2");
            app.UseRewriter(options);

            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                   name: "default",
                   template: "{action=Index}/{id?}",
                   defaults: new { controller = "Home" }
                   );
        });
    }

1 个答案:

答案 0 :(得分:2)

问题是.AddRedirect和.AddRewrite只查看URL的路径/查询字符串。所以你的正则表达式是正确的,但是方法只是查看路径/查询,所以它永远不会看到www。这种行为是大多数重写器的标准,例如Apache mod_rewrite和IIS UrlRewrite。但是,应该很容易支持这个用例,我们很快就会对其进行调查!

目前,要获得预期的行为,您可以创建这样的自定义规则。注意我现在无法测试代码,但总体思路应该是正确的。

        app.UseRewriter(new RewriteOptions().Add(ctx =>
        {
            // checking if the hostName has www. at the beginning
            var req = ctx.HttpContext.Request;
            var hostName = req.Host;
            if (hostName.ToString().StartsWith("www."))
            {
                // Strip off www.
                var newHostName = hostName.ToString().Substring(4);

                // Creating new url
                var newUrl = new StringBuilder()
                                      .Append(req.Scheme)
                                      .Append(newHostName)
                                      .Append(req.PathBase)
                                      .Append(req.Path)
                                      .Append(req.QueryString)
                                      .ToString();

                // Modify Http Response
                var response = ctx.HttpContext.Response;
                response.Headers[HeaderNames.Location] = newUrl;
                response.StatusCode = 301;
                ctx.Result = RuleResult.EndResponse;
            }
        }));