Redirecting Old Pages with IIS 7 and the URL Rewrite Module

Posted: December 11, 2012 in Asp.net, c#, IIS

An elegant way to handle change when it comes to renaming and moving pages around within an ASP.NET web application is to take advantage of the IIS 7 Rewrite module.  With this strategy in place I can easily add redirects to a single xml file and update it as needed.

Here’s how to get it setup:

  • Make sure you have the URL Rewrite module installed in IIS 7.
  • Add a file called Web.RewriteMaps.config to your web application root.  This is the file that will contain all your redirect mappings.  It should look like this:
  • <rewriteMaps>
      <rewriteMap name="OldPages">
        <add key="/oldpage.aspx" value="/newstuff/newpage.aspx" />
        <add key="/legacy/really_old.aspx" value="/BrandNew.aspx" />
      </rewriteMap>
    </rewriteMaps>
  • Add the following to the <system.webServer/> section of your web.config file.  If you already have a <rewrite/> section don’t duplicate but merge the following in.
        <rewrite>
          <rewriteMaps configSource="Web.RewriteMaps.config"/>
          <rules>
            <rule name="Old Page Redirects" stopProcessing="true">
              <match url=".*"/>
              <conditions>
                <add input="{OldPages:{REQUEST_URI}}" pattern="(.+)"/>
              </conditions>
              <action type="Redirect" url="{C:1}" appendQueryString="false" redirectType="Permanent"/>
            </rule>
          </rules>
        </rewrite>
  • That’s it.  Now IIS will read you Web.RewriteMaps.config file and perform a ”301 Moved Permanently” on all your old pages and redirect the user to the new page.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s