ASP.NET rewrite

Rewrite addresses with (mod_rewrite) with ASP.NET.

Using so-called “Pretty URLs” have become increasingly common to increase the usability of applications. It may also have some benefits to the websites chances of a good placement in search engines.

On our UNIX servers, it is very easy via mod_rewrite to rewrite URLs but those who prefer Windows, and ASP.NET has not the same opportunity to use mod_rewrite. However, there is a nice solution that is simple and does not require any additional installation on the server: UrlRewriter.NET.

How to use UrlRewriter.NET?

1. [Download] and unpack

2. Add a reference to Intelligencia.UrlRewriter.dll that you also put in your project’s “bin” directory.

3. Open your web.config file

4. Add the following

RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
name="UrlRewriter" />

You are now ready to rewrite URLs! Below are some examples.

Our application is a web shop that sells various types of media. In the current situation, we have a page that lists all products in a category as follows: and this we want to shorten to

Open your web.config file where you added UrlRewriter.NET and add the following rule:

<rewrite url="~/dvd.aspx" to="~/products.aspx?category=dvd" />

This works great if you have a small amount of categories. But if you have many categories it soon becomes unwieldy to add each new category manually. With the help of a regular expression, we can generalize the rule in the example above.

<rewrite url="~/shop/(.+).aspx" to="~/products.aspx?category=$1" />

This example rewrites all variants of to

Perfect, then we can show the different categories. It would be useful to be able to view a summary of every product. This can be done by extending the rule above by adding one more argument.

<rewrite url="~/shop/(.+)/(.+).aspx" to="~/products.aspx?category=$1&product=$2" />

In this way, your customers can write for example which rewrites to

Of course it is possible to extend the example on indefinitely if we categorize their products even deeper.

Was this article helpful?

Related Articles