Since Umbraco 9 changed its underlying framework to .NET 5, we are no longer able to make use of the web.config to configure our IIS Rewrite Rules. Let's take a look at the new way of configuring IIS Rewrite rules in Umbraco 9, using the ASP.NET Core URL Rewriting Middleware!
To get started with using the IIS Url Rewriting Middleware, we first have to create our rewrite rules. We do this by creating an .xml file in our project to contain our rules. For simplicity, we will be placing it in the root of our project. (Tip! Don't forget to configure your Build/Publish to copy over this file!)
An example of what a rewrites.xml file may look like:
The example shown above will automatically remove all trailing slashes from the URL, except if we're accessing a file, folder, or anything starting '/umbraco'.
Now we have to configure our Umbraco application to use said file! We do this by creating a new instance of RewriteOptions() which will accept our IIS config file as a parameter. We then pass these options into the UseRewriter extension method of our app in the Startup.cs Configure method as follows:
EDIT: It is now also possible to use an overloaded version of the AddIISUrlRewrite method that does not require us to open a streamreader! We end up with the following additions to our Startup.cs Configure method instead:
And that's it! If we were to head to any page of our Umbraco site and append a slash to the URL, we will automatically be given a Permanent (301) Redirect to the non-slash variant!
If you are interested in some interesting/common URL Rewrite Rules, you can check out the Umbraco Docs for some examples and links to other interesting sites: https://our.umbraco.com/documentation/Reference/Routing/IISRewriteRules/ 🔥
If you have any further questions, feel free to contact me over at my socials available at the Contact page, and I'd love to hear about the amazing creations you're able to come up with! 😄
Sources used in this article:
Umbraco Documentation, https://our.umbraco.com/documentation/Reference/Routing/IISRewriteRules/
Microsoft Documentation, https://docs.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-5.0
Changes made to this article:
30-04-2022, Added the AddIISUrlRewrite method variant that does not require the use of a streamreader.