ASP.NET Core 1.1 Url Rewriting - www for non-www

Here's the kernel I'm using with ASP.NET Core 1.1 Url, rewriting middleware for redirection from www. non-www:

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

and for some reason it is not working. I know that regex is correct. What is wrong here?

Here's the full Configure function:

        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" }
                   );
        });
    }
+4
source share
1 answer

, .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;
            }
        }));
+2

Source: https://habr.com/ru/post/1664078/


All Articles