【问题标题】:ASP.NET Core 1.1 Url Rewriting - www to non-wwwASP.NET Core 1.1 Url 重写 - www 到非 www
【发布时间】:2017-05-03 11:48:46
【问题描述】:

这是我使用 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" }
                   );
        });
    }

【问题讨论】:

  • 为什么你确定正则表达式是正确的? “www\\”的意思是“www\.example.com”。顺便说一句 this tool 可以帮助你。
  • 是的,这是正确的 - ^(www\.)(.*)$ ,我必须转义“点”
  • @ChristianGollhardt \\ 用于 C# 字符串,转换为 \ 用于正则表达式。
  • 好吧,看起来很奇怪。根据this example,您做得对。也许我们需要以某种方式包含protokoll? msdn 示例是否适合您(删除尾部斜杠)?假设......核心在我的待办事项列表上。
  • 它怎么不起作用 - 它只是被忽略了吗?你能粘贴你Configure方法的所有相关部分吗?

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


【解决方案1】:

问题在于 .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;
            }
        }));

【讨论】:

  • 我还需要添加://var newUrl = $"{request.Scheme}://{domain}{request.PathBase}{request.Path}{request.QueryString}";
猜你喜欢
  • 2014-12-16
  • 2015-11-06
  • 1970-01-01
  • 2011-06-24
  • 2019-03-09
  • 2011-11-05
  • 2013-12-20
  • 1970-01-01
  • 2017-10-05
相关资源
最近更新 更多