Managing Canonical Host Name – IIS Rewrite Rules

Managing Canonical Host Name – IIS Rewrite Rules

Description

Google Analytics generates statistics for a single domain so you need to determine the URL you want people to see.
For instance, if someone types in http://mywebsite.com, then the user could be redirected to http://www.mywebsite.com. This way every page of the website would be accessed with the complete address including the protocol HTTP and WWW subdomain.
The canonical URLs help to make your links Search Engine Optimized (SEO) and also improve link and ranking signals for content available through multiple URL structure or via syndication.
In addition, if the website uses SSL certificate then it is important to redirect the user to the determined domain and also keep the HTTPS protocol.

Solution

The IIS 7 and superior versions use the web.config file to handle canonical URLs.
You can copy and paste the code below and put this on your web.config under the <system.webServer> tag.

 

<rewrite>
    <rules>
        <rule name="CanonicalHostnameNoHTTPS" enabled="false" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
            <add input="{HTTPS}" pattern="OFF" />
            <add input="{HTTP_HOST}" matchType="Pattern" pattern="^mywebsite.com$" ignoreCase="true" negate="true" />
          </conditions>
          <action type="Redirect" url="http://www.mywebsite.com/{R:1}" />
        </rule>
        <rule name="CanonicalHostnameWithHTTPS" enabled="false">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
            <add input="{HTTPS}" pattern="ON" />
            <add input="{HTTP_HOST}" pattern="^mywebsite.com$" negate="true" />
          </conditions>
          <action type="Redirect" url="https://www.mywebsite.com/{R:1}" />
        </rule>
    </rules>
</rewrite>

 

After copying the code, open the IIS and go to URL Rewrite.
From there you will be able to see the rules you just created and also test them by clicking twice on the rule and then click on ‘Test pattern…’ button.

URL Rewrite

You could write redirection rules in many different ways so it is always a good idea to test them on the IIS.
Thank you

Leave a Comment

%d bloggers like this: