IIS URL Rewrite Gotcha

When using Visual Studio, and starting a website using F5 or ctrl-F5, the website displayed is the live website and not the localhost website on your development machine. Why?

URL Rewrite Add RuleThe problem can be caused by , for example, using url rewrite to force your website to use the www prefix.

Using the rule template Canonical domain name the code generated in the web.config file will look like rule CanonicalHostNameRule1, shown below:

What it means is that any {HTTP_Host} that does not match www. example .com will be redirected to www. example. com.

This will also include http://localhost:12345/,  the local web address used by visual studio.

Fortunately, many developers system may not have the URL Rewrite module installed (it is a separate download), and therefore will not encounter this problem. Unfortunately, it could take some developers by surprise if this module is downloaded at a later date, and they find that whilst trying to debug their website on their local machine, they find their browser displaying the live website.

One further quirk, is that even when you find the offending rewrite rule in the web.config and remove it, there appears to be some sort of persistent memory that will remember the permanent redirect and the debug session will still be redirected to the live site (http:///www.example.com).

Any comments on how to remove this ‘persistent’ memory of the 301 redirect would be most useful for those confronted by this issue.
<rewrite>
<rules>
<rule name="CanonicalHostNameRule1">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\.example\.com$" negate="true" />
</conditions>
<action type="Redirect" url="http://www.example.com/{R:1} redirectType="Permanent" />
</rule>
</rules>
</rewrite>

This issue can be easily worked around by editing the rule manually to the following:


<rewrite>
<rules>
<rule name="Add WWW prefix">
<match url="(.*)" ignoreCase="true" />
<conditions>
<add input="{HTTP_HOST}" pattern="^example\.com$" />
</conditions>
<action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>

Any insights on the pros and cons of the above two rules would be welcomed.

A final note to anyone looking at URL rewrite is that Pluralsight have an excellent course by Scott Forsyth entitled URL Rewrite for Developers.

Advertisements