Fabien ESCOFFIER
Fabien ESCOFFIER

Reputation: 4911

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.

Upvotes: 11

Views: 2098

Answers (1)

natemcmaster
natemcmaster

Reputation: 26783

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);

Upvotes: 14

Related Questions