I am trying to re-write my URL for the 3 following condition: 1. Remove .php extention 2. Remove .html extention 3. redirect all "www" to non-www
I was trying to use the ASP Core's Rewrite package and run the following code:
app.UseRewriter(new RewriteOptions().AddIISUrlRewrite(env.WebRootFileProvider, "files/IISUrlRewrite.xml"));
on files/IISUrlRewrite.xml, I have this code:
<rewrite>
<rules>
<rule name="RemovePHP">
<match url="^(.*).php$" />
<action type="Rewrite" url="{R:1}" />
</rule>
<rule name="RemoveHTML">
<match url="^(.*).html" />
<action type="Rewrite" url="{R:1}" />
</rule>
<rule name="www to non-www" stopProcessing="true">
<match url="(www.*)" negate="false"></match>
<action type="Redirect" url="http://example.com/{R:1}"></action>
<conditions>
<add input="{HTTP_HOST}" pattern="^example\.com$" negate="true"></add>
</conditions>
</rule>
</rules>
</rewrite>
However, this is not working. www's are not being redirected, .php are not being removed. This code works fine when I put it in my web.config file.
Also, I understand I could do the same thing using the middleware Microsoft Documentation: Url Rewriting
Thank you for the help.
This usually happens when you add the RewriteMiddleware after configuring the static file handling using the app.UseStaticFiles()
method: if you do that, the RewriteMiddleware might be superseeded by the one in charge of the static files, which could mess up your rewrite rules.
In other words, do not do this:
app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions(...));
app.UseRewriter(new RewriteOptions(...)); // <- MIGHT NOT WORK AS EXPECTED
And do this instead:
app.UseDefaultFiles();
app.UseRewriter(new RewriteOptions(...)); // <- WORKS
app.UseStaticFiles(new StaticFileOptions(...));
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