Tuesday, March 31, 2009

.NET/IIS URL Rewriting using URL Rewriter

You can easily rewrite URLs on .NET/IIS using free open source program called URL Rewriter.
If you don't know what is URL rewriting is, it is simply the mechanism which give out search engine friendly URL like example.com/products/psp instead of example.com/products.aspx?product=psp
Whats actually happening is, there is only products.aspx file exists and it takes query sting product.
But by using URL rewriting, it passes the psp as the query string to the products.aspx file.
So what user see is example.com/products/psp but (s)he is actually looking at the example.com/products.aspx?product=psp.

So Interested? ;-)
If so this is how it will be done,

<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>

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

  • Now if you test this on Visual Studio, you will see that URL rewriting is working.
  • But, If you deploy this on ISS it will not work.
  • The trick is,
  • Right Click on the web site on ISS manager.
  • Goto the "Home Directory" tab.
  • Select configurations.
  • Select .asax extension.
  • Click "Edit" button.
  • Copy the executable path and click the "Cancel" button.
  • Now click on the "Insert" button.
  • Paste the previously copied executable path on the text box.
  • Make sure that "Verify that file exists" is unchecked.
  • Click Ok
  • Close the web site properties dialog.
  • And thats it. ;-)
You can use reguler expressions, IF clause, UNLESS clause etc. URL handling. You can find out lot about it from URL Rewriter Refence.