September 8, 2013
Why the default IIS canonical domain rule breaks dev/staging traffic, and a pattern-matching fix that only enforces the canonical domain in production.
The default Canonical Domain Name rule in IIS doesn't work very well.
The generated rule doesn't work across different sub domains for example. The rule that's generated in IIS produces this code in the web.config file:
<rule name="Canonical Host Name" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" negate="true" pattern="^www\.tekcent\.com$" />
</conditions>
<action type="Redirect" url="http://www.tekcent.com/{R:1}" redirectType="Permanent" />
</rule>Problem with the default IIS rule
This rule doesn't work for us since it redirects any request from localhost or staging.* to our production website. An improved version addresses this limitation.
Improved rule
<rule name="Canonical Host Name" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^tekcent.com$" />
</conditions>
<action type="Redirect" url="http://www.tekcent.com/{R:1}" redirectType="Permanent" />
</rule>
This rule checks for an exact match on tekcent.com so sub domains such as staging.tekcent.com and localhost are allowed through. The approach works because canonical domain enforcement is only needed in production environments.