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

<configSections>
<section
name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.
RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</configSections>
<system.web>
<httpModules>
<add
type="Intelligencia.UrlRewriter.RewriterHttpModule,
Intelligencia.UrlRewriter"
name="UrlRewriter" />
</httpModules>
</system.web>

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: example.com/products.aspx?category=dvd and this we want to shorten to example.com/dvd.aspx.

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

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

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.

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

This example rewrites all variants of example.com/shop/dvd.aspx to example.com/products.aspx?category=dvd.

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.

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

In this way, your customers can write for example example.com/shop/dvd/terminator2.aspx which rewrites to example.com/products.aspx?category=dvd&product=terminator2.

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

Was this article helpful?

Related Articles