You can download the example discussed in this post here.
Why rewrite?
The default URLs from ASP.NET Webforms (and possibly even MVC) are not fantastic for SEO (Search Engine Optimisation).
You know the sort:
http://example.com/Questions/Question.aspx?ID=345
Google doesn’t really like URLs like this. It doesn’t say much about the page it represents. It might have an idea that it’s something to do with question 345 but that could mean anything. The file extension (.aspx) doesn’t help either.
What Google likes to see, is something a bit more like this:
http://example.com/questions/345/how-do-i-do-something
Well with Webforms you’re a little stuck, as the URL is dependent on the file structure of your solution and name of the files.
Unless..
..you perform some voodoo URL rewriting.
Example setup
We are going to map an incoming request to a URL like this..:
http://localhost:52468/questions/1337/how-do-i-do-something
..to the default page URL like this:
http://localhost:52468/Default.aspx?ID=1337
To achieve this I’m going run through a very simple rewriting setup.
- I will be using Nick Berardi’s excellent (and free) Managed Fusion UrlRewriter.
- I am only going to be covering the absolute bare minimum to get you going.
Nick has a more detailed example here and you should also check out Scott Guthrie’s post here. (N.B. My example is based on Nick’s)
First, create a standard web application:
Then download UrlRewriter from Managed Fusion. Unzip it, put the dll and pdb in a directory of your choosing and add a reference to the dll.
Next, create a new text file called ManagedFusion.Rewriter.txt and place the following in it:
In your Web.Config, add (or copy from the example) these following sections:
configuration -> configSections ->
configuration ->
configuration -> system.web -> httpModules ->
configuration -> system.webServer ->
On the opening modules tag, set runAllManagedModulesForAllRequests to true and add the RewriterModule so is becomes:
configuration -> system.webServer -> handlers ->
And that’s it!
Note that the application actually ignores the slugs at the end of the URL so your app can generate what it likes for them.
Also note that the rewrite rules can be far more complex than what is shown in the example. UrlRewriter’s rules are based on the Apache module, mod_rewrite.
Further reading:
- Stackoverflow Question: ASP.NET URL Rewriting
- Managed Fusion Url ReWriter
- ScottGu’s post: ‘Tip/Trick: Url Rewriting with ASP.NET’
3 comments:
I think you need to 'rewrite' the last link in your post, to Scott Gu's post ;)
Oops. Thanks Mike!
I noticed it aswell
Post a Comment