Redirecting to Canonical URL in IIS7

January 14, 2010

If you are using IIS7, it’s very easy to ensure that all requests always go to your preferred canonical URL. It’s a two step process:

Step 1: Install the UrlRewrite module for IIS: Rewrite

Step 2: Add the following rule to your applications web.config file:

        <clear />
        <rule name="Redirect from www" stopProcessing="true">
           <match url=".*" />
              <add input="{HTTP_HOST}" pattern="^$" />
           <action type="Redirect" url="{R:0}" redirectType="Permanent" />

IMPORTANT: When using the above code, take care to merge it with your existing web.config without duplicating any existing elements.

I like my URL’s to be in the format If you prefer, simply remove “www.” from the <add> element and add it to the <action> element’s “url” attribute.