random .NET and web development musings

For those of you still running IIS6 who would like to have nice SEO friendly URLs, one option is to use ISAPI Rewrite.

First, add a “.mvc” handler mapping to the asp.net dll as per Phil Haacks post.

Obviously you’ll need ISAPI Rewrite installed, then you can create the following .htaccess file:

RewriteEngine on
AllowOverride All

# Ignore Assets folder
RewriteRule ^assets/(.*?)$ /assets/$1 [NC,L]

# Rewrite everything else to have .mvc on the end of the controller name
RewriteRule ^([^/]*)(/(?:.*?)*)?$ /$1.mvc$2 [NC,L]

I keep all my CSS, images and javascript under the /assets folder. If you have these elsewhere, you probably want to modify the first rewrite rule for your specific location.

N.B. you can probably ignore these folders in a much more elegant way, perhaps with a RewriteCond on the 2nd Rule. I’m not a master of this syntax yet so this will do for the time being, it works!

Some additional rules you may also want are the following:

# Rewrite favicon
RewriteRule ^favicon.ico(.*?)$ /assets/images/icons/favicon.ico [NC,L]

# Rewrite appleicon
RewriteRule ^apple-touch-icon.png(.*?)$ /assets/images/icons/apple-touch-icon.png [NC,L]

# Ignore robots.txt
RewriteRule ^robots.txt(.*?)$ /robots.txt [NC,L]

Adding the following to your global.asax:

protected void Application_BeginRequest()
{
	if (this.Request.AppRelativeCurrentExecutionFilePath.Contains(".mvc"))
		this.Context.RewritePath(this.Request.Url.PathAndQuery.Replace(".mvc", string.Empty));
}

means you don’t need to have the .mvc in your route configurations, which keeps things nice and tidy!

NO COMMENTS
Post a comment