Monday 8 March 2010

The power of the IIS7 url rewrite module

Having only recently got into IIS7 after buying a new web server, I am pleased to see that version 7 is somewhat following apache's lead by allowing modules to be plugged into the server. If you host anything beyond a very basic website in IIS 7, you will likely have the need to use http modules, very likely including some kind of url rewiting.

There can be many reasons to do url rewriting - Search Engine Optimization (friendly urls), Redirection to a secure site, or changing the request in some other way.

With IIS 6 you would either have to pay for a 3rd party ISAPI dll to do some of these, or spend time programming them yourself. But now the IIS 7 url rewrite module is here to come to the rescue.

All this involes is editing your web.config, using the new IIS7-only system.webServer configuration section (you can also do it through IIS Manager). Here are 2 examples.

The first rule I have created below redirects requests starting with "http" to the equivalent "https" url. You can do this for a specific area within your application too - just add another web.config within that subfolder with appropriate rules inside it's system.webServer -> rewrite section. You can also use tags if you want to keep all web.config stuff in one file. E.g.:

<location path="admin"><system.webserver><rewrite>... your rules...</rewrite></system.webserver></location>

The second rule redirects requests not containing www (e.g.: http://yoursite.com) to the url containing www. You can do the opposite quite easily too.

<system.webServer>
...
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<!-- Require SSL must be OFF in the site settings -->
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}{REQUEST_URI}" />
</rule>
<rule name="Non www to www redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\.yoursite\.com$" ignoreCase="true" negate="true" />
</conditions>
<action type="Redirect" url="https://www.{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>

See also the official documentation for the IIS7 url rewriting module.

No comments: