Woo-hoo!
// ...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
// ...
}
else
{
// url rewrite; do this before UseStaticFiles
var options = new RewriteOptions().Add(
new RedirectRules(rewriteHttps: true, rewriteWww: true));
app.UseRewriter(options);
}
// ...
}
// ...
public class RedirectRules : Microsoft.AspNetCore.Rewrite.IRule
{
private readonly bool _rewriteHttps;
private readonly bool _rewriteWww;
public RedirectRules(bool rewriteHttps, bool rewriteWww)
{
_rewriteHttps = rewriteHttps;
_rewriteWww = rewriteWww;
}
public void ApplyRule(RewriteContext context)
{
//
// redirect two ways
// - http to https (if enabled)
// - non-www host to www host (if enabled)
//
const string hostRoot = "mydomain.com";
var request = context.HttpContext.Request;
var currentHost = request.Host;
HostString newHost;
// do we need to rewrite from http to https
var isNewProtocol = _rewriteHttps && request.Scheme.ToLower() == "http";
// do we need to rewrite from non-www host to www host
if (_rewriteWww && currentHost.Host == hostRoot)
newHost = new HostString($"www.{hostRoot}", currentHost.Port ?? 80);
// if either rewrite done, create a new url
if (isNewProtocol || newHost.HasValue)
{
var newUrl = new StringBuilder()
.Append(isNewProtocol ? "https" : request.Scheme)
.Append("://")
.Append(newHost.HasValue ? newHost : currentHost)
.Append(request.PathBase)
.Append(request.Path)
.Append(request.QueryString);
context.HttpContext.Response.Redirect(newUrl.ToString(), permanent: true);
context.Result = RuleResult.EndResponse;
}
}
}