Amazon.ca Widgets

Useful url rewrite rules for IIS

These are some rules I use in IIS to make all my web sites works as expected.

What I need to automate in all site:

  • Remove prefix “www.”
  • Redirect “http” to “https”, as http will soon disappear, thanks to LetsEncrypt.

Also, for very simple static sites, I want to make all pages respond to the same fixed static page, and get no 404.

You can do that without any code, when using the IIS Rewrite extension.  You first need to install the extension to your existing IIS configuration. (link)

This is an example of my IIS configuration:

  • Site 1: “https://foxontherock.com”
  • Site 2: “https://fredericmalenfant.com”
  • Site 3: default (ip binding)

Bindings strategy

The first strategy can be to add these rules to all your sites, one by one.
Exemple for site 1, these are the 4 bindings configuration:

  • http://foxontherock.com
  • http://www.foxontherock.com
  • https://foxontherock.com
  • https://www.foxontherock.com

If you set your IIS bindings like that, you need to add the rewrite rules to all your sites, one by one.

But there’s another simple strategy that I prefer, by using a “default” site on IIS.
On the first and second sites, I only set the “final” binding, e.g. foxontherock.com and fredericmalenfant.com, both on port 443 without www.

On the “default” site, I configure the bindings to respond to all other requests on my public IP address.

That way, I only need to add the redirect rules on the default site, as the redirection will be handled by the redirected site after.

IIS Rewrite Rules

First rule: Remove www prefix.

<rule name="Remove www" stopProcessing="true">
 <match url="(.*)" ignoreCase="true" />
 <conditions logicalGrouping="MatchAll">
  <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
 </conditions>
 <action type="Redirect" url="https://{C:1}/{R:0}" redirectType="Permanent" />
</rule>

Second rule: redirect http to https

<rule name="Redirect to https" stopProcessing="true">
 <match url="(.*)" />
 <conditions>
  <add input="{HTTPS}" pattern="off" ignoreCase="true" />
 </conditions>
 <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" redirectType="Permanent" />
</rule>

The third rule can be set to all sites, and is used to get a fixed page always responding, without 404.

<rule name="Default page" stopProcessing="true">
 <match url=".*" />
 <conditions>
  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
 </conditions>
 <action type="Rewrite" url="index.html" />
</rule>

Finally, you can add the “canonical” meta on that page to make robots index only 1 page, not all possible url.

(index.html)
<head>
...
<link rel="canonical" href="https://foxontherock.com/" />
</head>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.