Posts

ASP.NET Url rewrite module

Sep 7, 2018 | 2 minutes read

Tags: asp.net

I just received some feature requests from a client. The requests are about improving the site’s SEO rating. After adding the features, the site is now in the top 5 of google search results for “Auckland airport motel”. I used the rewrite module to move the site to SSL.

Below are sample rules that I believe are helpful to any site – the 2 rules below redirects to HTTPS, and picks a canonical host name (the one here is for Non-WWW).``

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Redirect to HTTPS">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTPS}" pattern="OFF" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" redirectType="Permanent" />
      </rule>
      <rule name="Canonical Host Name" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTP_HOST}" pattern="^www\." />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
<system.webServer>

The rewrite module does its job in three steps:

  1. Check if the incoming URL can be matched with the pattern inside the element
  2. If the optional element is available, further compare the URL pattern to other rules you specified
  3. If the incoming URL matches the pattern or passed the conditions, execute what is inside the element

I found that the rewrite module can perform 3 types of actions – Redirect, Rewrite, and Custom Action. I’ll just quickly write the main difference between a Redirect and a Rewrite.

A Redirect action type will change the address bar’s URL to what you specify in the element. A Rewrite will not change that URL and will just silently send the site visitor to the URL inside the element.

I’ll use this sample URL – http://:/? – to quickly explain the server variables used in the rules above:

the {HTTPS} variable checks if the request is secure

the {HTTP_HOST} variable grabs the part

the {REQUEST_URI} grabs the and the

The rewrite module is extremely flexible once you get comfortable with it. Microsoft’s detailed docs can be found here.