Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect www to non www rule in AspNetCore 1.1 preview 1 with RewriteMiddleware?

Using the AspNetCore 1.1 bits and the new RewriteMiddleware I wrote something like this into the Startup.cs to handle www to non www redirect :

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var options = new RewriteOptions()
        .AddRedirect("(www\\.)(.*)", "$1");

    app.UseRewriter(options);

    // Code removed for brevty
}

Since the RedirectRule only apply to the path and not the entire request uri, the regex does not match.

How can I redirect www to non www rule using the same approach ? I wouldn't like use the IISUrlRewriteRule.

like image 661
Fabien ESCOFFIER Avatar asked Oct 30 '16 23:10

Fabien ESCOFFIER


People also ask

How do I redirect in middleware net core?

In a browser with developer tools enabled, make a request to the sample app with the path /redirect-rule/1234/5678 . The regular expression matches the request path on redirect-rule/(. *) , and the path is replaced with /redirected/1234/5678 . The redirect URL is sent back to the client with a 302 - Found status code.


1 Answers

RewriteOptions allows you add a custom rule implementation. As you identified, the pre-written rules don't support redirecting hostnames. However, this is not too hard to implement.

Example:

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("http://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
            context.HttpContext.Response.Redirect(newUrl.ToString());
            context.Result = RuleResult.EndResponse;
        }
    }
}

You can add this to the Rules collection on RewriteOptions.

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

        app.UseRewriter(options);
like image 153
natemcmaster Avatar answered Oct 07 '22 12:10

natemcmaster