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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With