Storing URL rewrite mappings in a separate file

When using rewrite maps in IIS URL Rewrite it is very common to have a very large number of entries in a rewrite map. In order to avoid cluttering the configuration file – web.config – with this configuration data the rewrite maps can be defined in a separate configuration file. That file can then be referenced from the web.config file. This post provides an example of how this can be done.

Create a file called rewritemaps.config in the same directory where web.config file is. Open that file in notepad and add the following:

<rewriteMaps>
  <rewriteMap name="Redirects">
    <add key="/oldurl" value="/newurl" />
    <add key="/otheroldurl" value="/othernewurl" />
  </rewriteMap>
</rewriteMaps>

Save this file and then open web.config file in notepad. In the web.config file add the following inside of the <rewrite> section:

<rewriteMaps configSource="rewritemaps.config" />

The configSource attribute tells IIS configuration that the <rewriteMaps> section is defined in a separate file rewritemaps.config. This referenced section can be now uses as if it was defined in the same web.config file. Also, the IIS Manager UI will work well with this referenced file: when you modify or add entries to the rewrite map they will be stored in the rewritemaps.config file.

Here is a complete example web.config file that uses the rewrite map from referenced configuration file:

<configuration>
<system.webServer>
  <rewrite>
    <rewriteMaps configSource="rewritemaps.config"><rewriteMaps>
    <rules>
      <rule name="Redirect rule1 for Redirects">
        <match url=".*" />
        <conditions>
          <add input="{Redirects:{REQUEST_URI}}" pattern="(.+)" />
        </conditions>
        <action type="Redirect" url="{C:1}" appendQueryString="false" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>
</configuration>

The same approach can be used for storing rewrite rules in a separate configuration file, e.g.:

<rules configSource="rewriteRules.config" />