Reputation: 77
I was using IIS rewrite rules in web.config to do my HTTPS and non-www canonical URI enforcement, but then using Web Deploy became complicated so I switched to ASP.NET Core 6 middleware. Here's my code from Program.cs:
app.UseRewriter(new RewriteOptions().AddRedirectToNonWwwPermanent());
app.UseHttpsRedirection();
For http://example.com and https://www.example.com it works great and there is a single redirect.
But, for http://www.example.com it now implements the non-www rule, then the https rule, so you get two 308 redirects chained together (with IIS I had this with a single redirect).
You can test it here: https://www.redirect-checker.org/index.php
Enter: http://www.magazedia.com/
http://www.magazedia.com
308 Permanent Redirect
http://magazedia.com/
308 Permanent Redirect
https://magazedia.com/
200 OK
This plays havoc with my OCD.
Is there a simple fix or do I need to write a custom redirect that combines both?
EDIT:
I also just tried this, but the result is the same (double redirect):
app.UseRewriter(new RewriteOptions().AddRedirectToNonWwwPermanent().AddRedirectToHttpsPermanent() );
// app.UseHttpsRedirection();
Upvotes: 0
Views: 989
Reputation: 28067
As far as I know, the asp.net core url rewrite middleware also support using the url rewrite rule xml.
You could create a url reiwte xml named IISUrlRewrite.xml
and like below:
<rewrite>
<rules>
<rule name="Rewrite segment to id querystring" stopProcessing="true">
<match url="^iis-rules-rewrite/(.*)$" />
<action type="Rewrite" url="rewritten?id={R:1}" appendQueryString="false"/>
</rule>
</rules>
</rewrite>
Then modify the startup.cs(.net 5) or program.cs(.net 6)
using (StreamReader iisUrlRewriteStreamReader =
File.OpenText("IISUrlRewrite.xml"))
{
var options = new RewriteOptions()
.AddIISUrlRewrite(iisUrlRewriteStreamReader)
app.UseRewriter(options);
}
More details, you could refer to this article.
Upvotes: 2