Tuesday, April 24, 2007

URL Rewriting

I’ve been digging into URL rewriting recently. I want to take a request for a directory e.g: Http://www.mikehadlow.com/special/ And redirect it to a resource on a sub domain e.g: Http://features.mikehadlow.com/special_features.htm I first thought of using an HttpModule, but the problem is that it requires the request to be routed to the ASP.NET pipeline, but the ASP.NET pipeline is only invoked if the requested resource has an ASP.NET related file extension (.aspx, .asmx etc), a request for a directory will never invoke the ASP.NET pipeline, even if we ask HTTP.SYS to process all requests by doing a wildcard mapping to the ASP.NET handler (which is a bad idea anyway, since it creates a huge overhead for static content). It looks like the only way of doing this is to use an ISAPI extension like ISAPI_Rewrite (http://www.isapirewrite.com/). Reading up on it, this could be quite an elegant solution. It has built in redirection, so a simple configuration entry is all I would need to satisfy my requirements. The configuration file can be updated on the fly, so a little management interface would only have to do a simple file manipulation task to add, remove or edit redirects. It picks up the changes without requiring IIS to restart. I’ve downloaded the trial version, it seems to do the trick. I’ve experimented redirecting 'http://locahost/google' to 'http://www.google.com/', the only possible issue is that, because the browser is asked to redirect the url shown in the address bar changes to 'http://www.google.com/', but I’d get that with whatever solution I chose. The configuration file looks like this:
RewriteRule /google http://www.google.com [I,R]
There’s a free version that does per server URL rewriting, or a ‘pro’ version that costs $99 and allows per site configuration. Jeff Altwood talks about here. Update In my next post I realise that I can do the same thing by setting the HttpRedirect property in the IIS metabase. Also Travis Hawkins has a nice article here on using ISAPI_Rewrite. He also mentions another technique I hadn't considered before, of using the 404 error page to redirect unknown page requests to a generic handler. Travis also mentions RemapUrl, a tool that comes with the IIS 6.0 resource kit, but as he says, it's pretty limited.

No comments: