JustNik

How to remove first segment of a URL with an IIS Rewrite rule

Iislogo

Let's say you have the following URL structure being presented to the browser /section/news/article-title, but there isn't actually anything that can be served on that URL. In reality, the content that needs to be shown is available on /news/article-title, how can we either redirect to this URL or rewrite behind the scenes?

The answer, in this case, was to use an IIS rewrite rule. The solution is not the most robust, as it does rely on some fixed URL structure unfortunately, but this this is a legacy Umbraco project and this was the quickest solution to the problem.

So, knowing we have a fixed starting point in the URL and only the article-title segment changes we can use a quite simple, but quite clever IIS Rewrite rule to extract the article title, well actually it extracts everything that occurs after the fixed starting point of the URL.

The rule in question looks like this:

<rule name="Rewrite to article URL">
    <match url="^section/news/(.+)" />
    <action type="Rewrite" url="/news/{R:1}" />
</rule>

To explain what we are doing here, we are matching the whole URL for the inbound request, but we are only capturing the bit after the "fixed starting point", in this case /section/news (note, that the URL of the request actually doesn't start with a /).

Then, in this case, we are using a Rewrite response to rewrite the request to /news/ plus whatever is captured from the request group, referred to as . In IIS Rewrite rules the can be anything from 0 to 9 R capture groups. To learn more about these capture groups, I highly recommend having a read over the official Microsoft docs due to the complex nature of them.

NOTE Testing IIS rewrite rules is a PITA, if you can test them locally it's much easier but there is no easy way to check what each stage is doing. I highly wish there was!

JustNik
Connect with me
Twitter GitHub LinkedIn
© JustNik 2024