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: http://www.iis.net/expand/URLRewriteIIS Rewrite

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

<configuration>
 <system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Redirect from www" stopProcessing="true">
           <match url=".*" />
           <conditions>
              <add input="{HTTP_HOST}" pattern="^www.yoursite.com$" />
           </conditions>
           <action type="Redirect" url="http://yoursite.com/{R:0}" redirectType="Permanent" />
        </rule>
     </rules>
   </rewrite>
 </system.webServer>
</configuration>

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 http://mysite.com. If you prefer http://www.mysite.com, simply remove “www.” from the <add> element and add it to the <action> element’s “url” attribute.