Introduction
This article demonstrates the complete URL rewriting concept using regular expression and set up the predefined rules and handling the issue regarding post back of ASP.NET while requesting the virtual path of a Website.
Why does URL rewriting matter?
URL rewriting is one of the most common techniques used to lure search engines and provide search engine friendly URLs. As a developer, we want to write code that is the most flexible and easier to implement search engine friendly URLs.
Also, handling cases when you want to reconstruct the pages within your website and also take care of the old url which are kept as a bookmark by most of the user should not break during the page relocation.
Improve the search relevancy of the pages on your site using most regular search engine like Google, yahoo and Bing. Specifically, URL Rewriting can often make it easier to embed common keywords into the URLs of the pages on your sites, which can often increase the chance of someone clicking your link. Moving from using querystring arguments to instead use fully qualified URL's can also in some cases increase your priority in search engine results. Using techniques that force referring links to use the same case and URL entrypoint (for example: weblogs.asp.net/scottgu instead of weblogs.asp.net/scottgu/default.aspx) can also avoid diluting your pagerank across multiple URLs, and increase your search results.
Native URL mapping
It is possible that old URLs can map new URLs without writing any line of code by using the URL mapping concept in ASP.NET. To use this concept, just create a new urlMapping section under the system.Web section of your web.config file. As shown below.
<url Mapping enable=true>
<add url="~/Info/Copywrite.aspx" mappedurl="~/Help/CopyWrite.aspx" />
<add url="~/Info/Contact.aspx" mappedurl="~/Help/Contact.aspx" />
</url Mapping>
Note:-"~/ represent the root directory of the application"
This solution is fine and allows redirecting the user to the new location of the page. But user will may get surprises that during the postback the url is change from "http://www.metlab.com/Info/Copywrite.aspx" to "http://www.metlab.com/Help/CopyWrite.aspx". This happen because the ASP.NET engine fills the action attribute of the form with the new url.
<form action=" http://www.metlab.com/Help/CopyWrite.aspx" method="post" name="form1">
</form>
This approach is good and fruitful if we relocate a few number of pages only. If you have many files and URLs, this technique is not recommended.
URL Rewriting
The best way to implement a URL rewriting solution is to create reusable and easily configurable modules, so the obvious decision is to create an HTTP Module (for details on HTTP Modules see MSDN Magazine) and implement it as an individual assembly. To make this assembly as easy to use as possible, we need to implement the ability to configure the rewrite engine and specify rules in the web.config file.
During the development process we need to be able to turn the rewriting module on or off (for example if you have a bug that is difficult to catch, and which may have been caused by incorrect rewriting rules). There should, therefore, be an option in the rewriting module configuration section in web.config to turn the module on or off. So, a sample configuration section within web.config can go like this:
<rewriteModule>
<rewriteOn>true</rewriteOn>
<rewriteRules>
<rule source="(\d+)/(\d+)/(\d+)/" destination="Post.aspx?Year=$1&Month=$2&Day=$3"/>
<rule source="(.*)/Default.aspx" destination="Default.aspx?Folder=$1"/>
<rule source="Directory/(.*)/(.*)/(.*)/(.*).aspx" destination="Directory/Item.aspx?Source=$1&Year=$2&ValidTill=$3&Sales=$4"/>
<rule source="Directory/(.*)/(.*)/(.*).aspx" destination="Directory/Items.aspx?Source=$1&Year=$2&ValidTill=$3"/>
<rule source="Directory/(.*)/(.*).aspx" destination="Directory/SourceYear.aspx?Source=$1&Year=$2&"/>
<rule source="Directory/(.*).aspx" destination="Directory/Source.aspx?Source=$1"/>
</rewriteRules>
</rewriteModule>
This means all the request run likes: "http://localhost/Web/2006/12/10/ "redirect to the page known as Post.aspx.
To the above section in web.config file the developer should register a section name and section handler for this section. To do this, add a configsection section in web.config.
<configSections>
<sectionGroup name="modulesSection">
<section name="rewriteModule" type="UrlRewriteModule.UrlRewrittingModuleHandler"/>
</sectionGroup>
</configSections>
This means you can use the following section below the configurationsection
<modulesSection>
<rewriteModule>
<rewriteOn>true</rewriteOn>
<rewriteRules>
<rule source="(\d+)/(\d+)/(\d+)/" destination="Post.aspx?Year=$1&Month=$2&Day=$3"/>
<rule source="(.*)/Default.aspx" destination="Default.aspx?Folder=$1"/>
<rule source="Directory/(.*)/(.*)/(.*)/(.*).aspx" destination="Directory/Item.aspx?Source=$1&Year=$2&ValidTill=$3&Sales=$4"/>
<rule source="Directory/(.*)/(.*)/(.*).aspx" destination="Directory/Items.aspx?Source=$1&Year=$2&ValidTill=$3"/>
<rule source="Directory/(.*)/(.*).aspx" destination="Directory/SourceYear.aspx?Source=$1&Year=$2&"/>
<rule source="Directory/(.*).aspx" destination="Directory/Source.aspx?Source=$1"/>
</rewriteRules>
</rewriteModule>
</modulesSection>
Another thing we have to bear in mind that during the development of the rewriting module it should be possible to use the virtual url with the query string parameters, as shown in following:
"http://www.someblog.com/2006/12/10/?Sort=Dec&SortBy=Date".
Thus we have to develop the solution that can detect the parameters passed via query string and also via virtual url in webappication.
So, let's start by building a new Class Library. We need to add a reference to the System.Web assembly, as we want this library to be used within an ASP.NET application and we also want to implement some web-specific functions at the same time. If we want our module to be able to read web.config, we need to add a reference to the "System.Configuration" assembly.
Handling the Configuration Section
To reading the configuration section in web.config file we have to create a class that will implement the IConfigurationSectionHandler interface. As shown below.
namespace UrlRewriteModule
{
#region[Directive]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Web;
#endregion[Directive]
/// <summary>
/// This class has implemented IconfigurationSectionHandler to read configuration Section and
/// return it any form of object
/// </summary>
public class UrlRewrittingModuleHandler:IConfigurationSectionHandler
{
#region[PrivateVariable]
private XmlNode _xmlSection;
private string _rewriteBase;
private bool _rewriteOn;
#endregion[PrivateVarible]
#region[Poperty]
/// <summary>
/// gets or sets xmlSection
/// </summary>
public XmlNode XmlSection
{
get { return _xmlSection; }
set { _xmlSection = value; }
}
/// <summary>
/// gets or sets RewriteBase
/// </summary>
public string RewriteBase
{
get { return _rewriteBase; }
set { _rewriteBase = value; }
}
/// <summary>
/// gets or sets RewriteOn
/// </summary>
public bool RewriteOn
{
get { return _rewriteOn; }
set { _rewriteOn = value; }
}
#endregion[Poperty]
/// <summary>
///
/// </summary>
/// <param name="parent"></param>
/// <param name="configContext"></param>
/// <param name="section"></param>
/// <returns></returns>
public object Create(object parent, object configContext, XmlNode section)
{
// set base path for rewriting module to
// application root
_rewriteBase = HttpContext.Current.Request.ApplicationPath ;//+ "/";
// process configuration section
// from web.config
try
{
XmlSection = section;
RewriteOn = Convert.ToBoolean(section.SelectSingleNode("rewriteOn").InnerText);
}
catch (Exception ex)
{
throw (new Exception("Error while processing RewriteModule configuration section.", ex));
}
return this;
}
}
}
Amit PatelPosted Jun 22, 2012, 3:42 AM
Good one..
Manish TewatiaPosted Dec 22, 2011, 11:22 PM
Hi, Rahul thanx for be the part of mindcracker community. I have a question, take example of you own article as you can see in address bar a url same as your article title was generated. So, my question is that, is it possible to change this url after once its will be generated.....?
Stephen JohnsonPosted Dec 22, 2011, 11:18 PM
Great what an article. Thanks for sharing it.
Jimmy UnderwoodPosted Dec 22, 2011, 11:16 PM
Thanks for sharing this article
Akash AhlawatPosted Dec 22, 2011, 10:59 PM
Hey Rahul really a nice article..joy to read
Arjun PanwarPosted Dec 22, 2011, 10:54 PM
Really very nice article
Alok PandeyPosted Dec 22, 2011, 10:48 PM
Helpful article. Thanks for sharing.
Dinesh BeniwalPosted Dec 22, 2011, 11:25 AM
Good start, Welcome to the Mindcracker Community.