Best practice for managing Rewrite Rules in IIS7

When moving a client from an old site to a new one, you frequently need to redirect Legacy URLs to new ones to maintain SEO. IIS 7 Rewrite Rules with Rewrite Maps easily accomplish this. A Rewrite Map is simply a subset of a rule with a list of source/destinations. With a bit of massaging, you can take a Excel workbook and export to a map.

The only problem with IIS rewrites are they are added to the web.config file, which for a Sitecore app is already 4000+ lines. Here’s how to keep it clean:
Add the section everything inclusive of the <rewrite> tags just before the ending </system.webServer> tag.


<system.webServer>
    {lots of stuff here}
        <rewrite>
            <rewriteMaps configSource="RewriteMaps.config" />
            <rules configSource="RewriteRules.config" />
        </rewrite>
</system.webServer>

Add two files RewriteMaps.config and RewriteRules.config (samples below) to the web root. IIS will save any changes and additions to the external config files instead of the web.config.

In my starter files (below) are two rewrite maps, Legacy URLs and Marketing URL’s. Legacy would be for the old to new pages which will likely never change, and Marketing rules is for advertising campaigns etc. Keeping them segregated makes updates easier.

RewriteMaps.config

<rewriteMaps>
    <rewriteMap name="Legacy URLS">
        <add key="/about_directory.asp" value="/About/Find-an-Office.aspx" />
        <add key="foo" value="bar" />
    </rewriteMap>
    <rewriteMap name="Marketing Rules">
        <add key="/jobs" value="/AboutUs/Careers.aspx" />
    </rewriteMap>
</rewriteMaps>

RewriteRules.config

<rules>
    <rule name="Redirect rule1 for Legacy URLS">
        <match url=".*" />
        <conditions>
            <add input="{Legacy URLS:{REQUEST_URI}}" pattern="(.+)" />
        </conditions>
        <action type="Redirect" url="{C:1}" appendQueryString="false" />
    </rule>
    <rule name="Rewrite rule1 for Marketing Rules">
        <match url=".*" />
        <conditions>
            <add input="{Marketing Rules:{REQUEST_URI}}" pattern="(.+)" />
        </conditions>
        <action type="Rewrite" url="{C:1}" appendQueryString="false" />
    </rule>
</rules>

One thing to note with this: If you make changes to either of these files manually (in a text editor) it seems that IIS Caches them. So, after your done editing either of those files you need to open the web.config file and re-save it so it forces a refresh.