URL Redirection with Mod-Rewrite ISAPI filter

Date March 24, 2007 @ 12:52 pm in Microsoft.Net 2.0

Recently, one of our clients required that there entire site be optimized for search engines. As part of SEO our goal was to create hackable URL’s and avoid special characters on the query string. This meant no querystring arguments. We choose to use URL rewriting as a way to map dynamic virtual directories to database content.

Our goal was to take a friendly URL like below, and remap them to a more typical aspx page with arguments.

Input:
http://www.client.com/news/press/200703/aquisition
Output:
http://www.client.com/article.aspx?sectionid=22&issue=200703&name=acquisition

For the most part, URL rewriting in ASP.NET 2.0 is pretty straight forward. You create a class that implements System.Web.IHttpModule and register that class as a in the webconfig. All requests made to .aspx pages run through the handler prior to being redirected.

Unfortunately our goal for a friendly URL desired no file or extension, resulting in an interesting issue. Unless we placed a default.aspx page within each physical directory, the request would never fire through the ASP.NET process. Interestingly, ASP does not require this for the root of the site or once you hit 4 directories deep. In both of those situations, asp assumes default.aspx exists, resulting in the HtppModule firing.

Solution:

Our solution was to use a a free ISAPI filter called mod_rewrite (http://www.iismods.com/download.htm). This filter will allow us to append default.aspx to any requests that did not include a file with extension.

This filter is quite easy to use, it is completely configured via an INI file that uses regular expressions combined with back referencing to apply the rewrite. The following is the INI file we use to match requests with both a trailing slash “/” and without.

mod_rewrite.ini

Debug 1
Reload 2000
#Browse LOT
RewriteRule ^([^.]+)/([^/.]+)$ $1/$2/default.aspx
RewriteRule ^([^.]+)/$ $1/default.aspx

We have yet to test this under high load, but expect its performance to be adequate since it excludes everything but the page request.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">