Click here to Skip to main content
13,551,216 members
Click here to Skip to main content
Add your own
alternative version


49 bookmarked
Posted 11 Dec 2007
Licenced CPOL

URL Rewriting in ASP.NET 2.0

, 11 Dec 2007
Rate this:
Please Sign up or sign in to vote.
How to implement URL rewriting and improve your SEO rankings.


In this article, you will learn about URL rewriting in ASP.NET 2.0. URL rewriting was originally introduced by Apache as an extension called mod_rewrite. The concept of URL rewriting is simple. It allows you to rewrite those ugly URLs into better URLs, and hence it will perform better in SEO.

Most search engines will ignore dynamic URLs such as the ones ending with a querystring, e.g., Therefore, if you like to have more hits and traffic from search engines, consider rewriting all those querystring URLs into normal URLs.

If you rewrite the URL above, you can actually rewrite it into a more readable format, e.g., Or, you can rewrite it to

Search engine robots will think that your dynamic page is a normal page, and therefore will crawl your page, and thus your page will have better search results. If you check the pages in or, you can see that the web developers have used URL rewriting techniques.


Microsoft .NET Framework 2.0 comes with a limited URL rewriting library support, and you have to write your own URL rewriting engine if you need complex URL rewriting for your website. The simplest URL rewriting that you can achieve in seconds is by copying and pasting the code below to your global.asax file:

void Application_BeginRequest(Object sender, EventArgs e) 
 String strCurrentPath;
 String strCustomPath;
 strCurrentPath = Request.Path.ToLower();

 if (strCurrentPath.IndexOf("ID") >= 0) 
  strCustomPath = "/Product10.aspx";  
  // rewrite the URL

  Context.RewritePath( strCustomPath );

As you can see from the code above, the URL redirection is only limited to one rule. It will always redirect to a page called product10.aspx if it detects that your URL contains the ID keyword. Of course, this one will not work if you want a different querystring ID to redirect to a different page, or if you want to have different page redirection for different query string types.

To have more complex URL rewriting rules, we can use Regular Expressions for implementing different redirection techniques. Now, let's start writing some rules for your redirection.



As you can see from the first rule above, it will redirect a URL from product/(Number).aspx to displayProduct.aspx?ID=(Number). The second rule will redirect a URL if it contains Items/Mouse/(Number).aspx to ViewItem.aspx?ID=(Number). You can add as many rules as you like by just adding the XML node above.

void Application_BeginRequest(Object sender, EventArgs e)
    string sPath = Context.Request.Path;        
    //To overcome Postback issues, stored the real URL.

    Context.Items["VirtualURL"] = sPath;
    Regex oReg;
    XmlDocument xmlDoc = new XmlDocument();
    _oRules = xmlDoc.DocumentElement;

    foreach (XmlNode oNode in _oRules.SelectNodes("rule"))
        oReg = new Regex(oNode.SelectSingleNode("url/text()").Value);
        Match oMatch = oReg.Match(sPath);

        if (oMatch.Success)
            sPath = oReg.Replace(sPath, 

The code above is self explanatory. It will search from the rules in the XML file and if it matches, then it will rewrite the path. That's all you need to do to implement URL rewriting. However, after you rewrite the URL, all your page postbacks will not work. The reason is, ASP.NET will automatically output the "action" attribute of the markup to point back to the page it is on. The problem when using URL rewriting is that the URL that the page renders is not the original URL of the request. This means that when you do a postback to the server, the URL will not be your nice clean one.

To overcome this problem, you need to add this code on every page that you want to do a postback:

protected override void Render(HtmlTextWriter writer)
    if (HttpContext.Current.Items["VirtualURL"] != null)
        string sVirURL= HttpContext.Current.Items["VirtualURL"].ToString()
        RewriteFormHtmlTextWriter oWriter = 
               new RewriteFormHtmlTextWriter(writer,sVirURL);


Source code for RewriteFormHtmlTextWriter

public class RewriteFormHtmlTextWriter : HtmlTextWriter
    private bool inForm;
    private string _formAction;

    public RewriteFormHtmlTextWriter(System.IO.TextWriter writer):base(writer)

    public override void RenderBeginTag(string tagName)
        if (tagName.ToString().IndexOf("form") >= 0)
    public RewriteFormHtmlTextWriter(System.IO.TextWriter writer, string action)
        : base(writer)

        this._formAction = action;

    public override void WriteAttribute(string name, string value, bool fEncode)
        if (name == "action")
            value = _formAction;
        base.WriteAttribute(name, value, fEncode);


That's all you need to implement a complex and fully extensible URL rewriting facility. You can create unlimited rules in your Rules.xml file and redirect to the page you want to.


In this article, you can see how easy it is to implement URL rewriting for your website. You can do enhancements and improve the workflow of the code above. For faster execution of your rules, you can also store the Rules.xml file as a caching object so it will save lots of time compared to opening and closing the XML file every time the rewrite happens.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

James Sullivan
United States United States
I work in a Software House Company in Malaysia (Kuala Lumpur) and I am MCP Certified in C# and Web Application course.

I originally started my programming in Java but later on changed to Microsoft platform because of the simplicity and ease of use.

I love .NET programming and am doing it almost every day now.
I normally post lots of my articles here
ASP.NET Tutorial

I also host my website at ASP.NET Web Hosting

You may also be interested in...

Comments and Discussions

QuestionCode is not working Pin
Member 1330768813-Jul-17 23:36
memberMember 1330768813-Jul-17 23:36 
GeneralMy vote of 4 Pin
Girish Nama4-Sep-13 19:46
memberGirish Nama4-Sep-13 19:46 
GeneralMy vote of 1 Pin
rahulmurari26-Apr-12 1:42
memberrahulmurari26-Apr-12 1:42 
GeneralContext.RewritePath(sPath); gives me Error Pin
Rizwan Bashir24-Jan-11 3:17
memberRizwan Bashir24-Jan-11 3:17 
QuestionRegarding URL Rewriting Pin
hemant.tawri3-Feb-10 22:58
memberhemant.tawri3-Feb-10 22:58 
GeneralHi, It seems It's not working...! Pin
Member 46587445-Jun-09 23:12
memberMember 46587445-Jun-09 23:12 
AnswerRe: Hi, It seems It's not working...! Pin
senylity10-Jun-09 4:46
membersenylity10-Jun-09 4:46 
GeneralAnother easy approach.. Pin
samardeep6-Apr-09 20:17
membersamardeep6-Apr-09 20:17 
GeneralFor Simplest Way of writing URL Rewriting Pin
DotNetGuts24-Jul-08 10:36
memberDotNetGuts24-Jul-08 10:36 
GeneralNice but... Pin
zhaojicheng11-Dec-07 16:50
memberzhaojicheng11-Dec-07 16:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04-2016 | 2.8.180515.1 | Last Updated 11 Dec 2007
Article Copyright 2007 by James Sullivan
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid