On an ASP.Net Core application startup I have:
RewriteOptions rewriteOptions = new RewriteOptions();
rewriteOptions.AddRedirectToHttps();
applicationBuilder.UseRewriter(rewriteOptions);
When in Production I need to redirect all Non WWW to WWW Urls
For example:
domain.com/about > www.domain.com/about
How can I do this using Rewrite Middleware?
I think this can be done using AddRedirect and Regex:
Github - ASP.NET Core Redirect Docs
But not sure how to do it ...
A reusable alternative would be to create a custom rewrite rule and a corresponsing extension method to add the rule to the rewrite options. This would be very similar to how AddRedirectToHttps works.
Custom Rule:
Extension Method:
Usage:
Future versions of the rewrite middleware will contain the rule and the corresponding extension method. See this pull request
It's unclear from if what AddRedirect method does and if it actually accepts regex.
But to insert a "www" to a url without "www"?
You could try it with these strings:
Because of the negative lookahead
(?!www[.])
after the protocol, it'll ignore strings like http://www.what.ever$1 and $2 are the first and second capture groups.
You don't need a RegEx, just a simple replace will work:
I think instead of using Regex unless it is a must you can use the Uri class to reconstruct your url
And the result will look like
I'm more of an Apache user and fortunately URL Rewriting Middleware in ASP.NET Core provides a method called
AddApacheModRewrite
to performmod_rewrite
rules on the fly.1- Create a
.txt
file whatever the name and put these two lines into it:2- then call it this way:
Done!
Here's a regex to try:
It will select URLs like:
http://example.com
https://example.com
http://example.gov
https://example.gov
http://example.org
https://example.org
But not like:
http://www.example.com
https://www.example.com
I prefer to use explicit extensions (e.g.
.com
,.gov
, or.org
) when possible, but you could also use something like this if it is beneficial to your use case:I would then approach the replacement with something like the following: