We use cookies for keeping user sessions alive and for site usage statistics.
Please accept cookies to continue browsing the site.

 

(You can decline cookies later navigating to page 'Privacy Policy'.)

IIS URL rewrite to canonical domain


It is considered good practice in view of search engines and site traffic analysis to always redirect from the "naked" domain like "mydomain.com" to the canonical domain "www.mydomain.com". This redirect should be done by the web server, before even getting to site code and content. To make IIS unconditionally redirect you need:
  • IIS version 7 and above
  • Microsoft IIS URL Rewrite 2 module installed (or supported by the hosting provider)
  • Code snippet below in your web.config file (at the root of your site)
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Enforce canonical hostname" stopProcessing="true">
          <match url="(.*)" ></match>
          <conditions>
            <add input="{HTTP_HOST}" pattern="^mydomain\.com$" ></add>
            <add input="{HTTP_HOST}" negate="true" pattern="^www\.mydomain\.com$" ></add>
            <add input="{SERVER_PORT_SECURE}" pattern="^0$" ></add>
          </conditions>
          <action type="Redirect" url="http://www.mydomain.com/{R:1}" redirectType="Permanent" ></action>
        </rule>
        <rule name="Enforce canonical hostname ssl" stopProcessing="true">
          <match url="(.*)" ></match>
          <conditions>
            <add input="{HTTP_HOST}" pattern="^mydomain\.com$" ></add>
            <add input="{HTTP_HOST}" negate="true" pattern="^www\.mydomain\.com$" ></add>
            <add input="{SERVER_PORT_SECURE}" pattern="^1$" ></add>
          </conditions>
          <action type="Redirect" url="https://www.mydomain.com/{R:1}" redirectType="Permanent" ></action>
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
Of course, you need to replace mydomain.com above with your domain name.
The IIS URL rewrite module is available here.

Back to List