Click here to Skip to main content
Click here to Skip to main content

URL Rewriting with ASP.NET

, 4 Jul 2002
Rate this:
Please Sign up or sign in to vote.
Demonstrates the use of regular expression-based URL Rewriting, similar to mod_rewrite with ASP.NET

How URL rewriting accepts a url and rewrites it

Introduction

One of the most popular extensions to the Apache webserver has been mod_rewrite - a filter which rewrites URLs. For example, instead of a URL such as

http://www.apache.org/BookDetails.pl?id=5
you could provide a filter which accepts URLs such as
http://www.apache.org/Book/5.html
and it will silently perform a server-side redirect to the first URL. In this way, the real URL could be hidden, providing an obfuscated facade to the web page. The benefits are easier to remember URLs and increasing the difficulty of hacking a website.

Mod_rewrite became very popular and grew to encompass a couple of other features not related to URL Rewriting, such as caching. This article demonstrates URL Rewriting with ASP.NET, whereby the requested URL is matched based on a regular expression and the URL mappings are stored in the standard ASP.NET web.config configuration file. ASP.NET includes great caching facilities, so there's no need to duplicate mod_rewrite's caching functionality.

As more and more websites are being rewritten with ASP.NET, the old sites which had been indexed by google and linked from other sites are lost, inevitably culminating in the dreaded 404 error. I will show how legacy ASP sites can be upgraded to ASP.NET, while maintaining links from search engines.

ASP.NET support for URL Rewriting

ASP.NET provides very limited support out of the box. In fact, it's support is down to a single method:

void HttpContext.RewritePath(string path)
which should be called during the Application_BeginRequest() event in the Global.asax file. This is fine as long as the number of URLs to rewrite is a small, finite, managable number. However most ASP sites are in some way dynamic, passing parameters in the Query String, so we require a much more configurable approach.

The storage location for all ASP.NET Configuration information is the web.config file, so we'd really like to specify the rewrites in there. Additionally, .Net has a fast regular expression processor, giving free and fast search and replace of URLs. Let's define a section in the web.config file which specifies those rewrites:

<configuration>
  <system.web>
        <urlrewrites>
            <rule>
                <url>/urlrewriter/show\.asp</url>
                <rewrite>show.aspx</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/wohs\.asp</url>
                <rewrite>show.aspx</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/show(.*)\.asp</url>
                <rewrite>show.aspx?$1</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/(.*)show\.html</url>
                <rewrite>show.aspx?id=$1&amp;cat=2</rewrite>
            </rule>
            <rule>
                <url>/urlrewriter/s/h/o/w/(.*)\.html</url>
                <rewrite>/urlrewriter/show.aspx?id=$1</rewrite>
            </rule>
        </urlrewrites>
    </system.web>
</configuration>

Notice how we have to escape the period in the url element such as 'show\.asp'. This is a Regular Expression escape and it's a small price to pay for the flexibility of regular expressions. These also show how we set-up a capturing expression using (.*) in the <url> element and refer to that capture in the <rewrite> element with $1

Configuration Section Handlers

.Net's configuration mechanism requires us to write code as a "handler" for this section. Here's the code for that:

<configuration>
    <configSections>
        <sectionGroup name="system.web">
          <section name="urlrewrites" type="ThunderMain.URLRewriter.Rewriter,
              ThunderMain.URLRewriter, Version=1.0.783.30976,
              Culture=neutral, PublicKeyToken=7a95f6f4820c8dc3"/>
        </sectionGroup>
    </configSections>
</configuration>

This section handler specifies that for every section called "urlrewrites", there is a class called ThunderMain.URLRewriter.Rewriter which can be found in the ThunderMain.URLRewriter.dll assembly with the given public key token. The public key token is required because this assembly has to be placed into the GAC and therefore given a strong name.

A section handler is defined as a class which implements the IConfigurationSectionHandler interface. This has one method, Create(), which should be implemented, and in our code that is very simple. It merely stores the urlrewrites element for later use:

public object Create(object parent, object configContext, XmlNode section) 
{
    _oRules=section;

    return this;
}

Initiating the rewrite process

Coming back to actually rewriting the URL, as I said earlier, we need to do something in the Application_BeginRequest() event in Global.asax - we just delegate this to another class:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    ThunderMain.URLRewriter.Rewriter.Process();
}

which calls the static method Process() on the Rewriter class. Process() first obtains a reference to the configuration section handler (which happens to be an instance of the current class) and then delegates most of the work to GetSubstitution() - an instance method of this class.

public static void Process() 
{
    Rewriter oRewriter=
       (Rewriter)ConfigurationSettings.GetConfig("system.web/urlrewrites");

    string zSubst=oRewriter.GetSubstitution(HttpContext.Current.Request.Path);

    if(zSubst.Length>0) {
        HttpContext.Current.RewritePath(zSubst);
    }
}

GetSubstitution() is just as simple - iterating through all possible URL Rewrites to see if one matches. If it does, it returns the new URL, otherwise it just returns the original URL:

public string GetSubstitution(string zPath) 
{
    Regex oReg;

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

        if(oMatch.Success) {
            return oReg.Replace(zPath,
                             oNode.SelectSingleNode("rewrite/text()").Value);
        }
    }

    return zPath;
}

Installing the sample code

Extract the code into a URLRewriter folder, then turn this into a virtual directory using the Internet Information Services MMC control panel applet. Compile the code use the 'Make Rewriter.bat' batch script into the bin sub-folder. Then add bin/ThunderMain.URLRewriter.dll to the Global Assembly Cache by copying and pasting the dll into %WINDIR%\assembly using Windows Explorer. Finally, navigate to http://localhost/URLRewriter/default.aspx and try the demo URLs listed.

None will actually work because there's one last thing we have to be aware of...

Finally

There's one major caveat with all this. If you want to process a request with a file extension other than .aspx such as .asp or .html, then you need to change IIS to pass all requests through to the ASP.NET ISAPI extension. Unfortunately, you will need physical access to the server to perform this, which prevents you from simply XCOPY deploying your code to an ISP.

Adding a mapping for all file types

We've added the HEAD, GET and POST verbs to all files with .* file extension (ie all files) and mapped those to the ASP.NET ISAPI extension - aspnet_isapi.dll.

A mapping for all file types has been added

The complete range of mappings, including the new .* mapping.

License

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

Share

About the Author

Richard Birkby
Web Developer
United Kingdom United Kingdom
Richard Birkby is a software engineer from London, UK, specializing in .Net. Richard has coded for many different sized companies from small venture-capital funded start-ups, to multi-national corporations (ie Microsoft). When he's not programming, he enjoys driving his sports car or eating curry (although never at the same time!).
 
Richard helps run CurryPages.com and has several other covert ventures in development. Stay tuned!

Comments and Discussions

 
QuestionYour code does not worked on IIS PinmemberA. Najafzadeh17-Jun-14 18:28 
Question500 -internal error showing after rfreshing website Pinmembermithss10-Dec-13 2:40 
QuestionRewrite URL Pinmembermmani55527-Jan-13 23:15 
QuestionURL REDIRECTION PinmemberMember 917112831-Jul-12 20:03 
QuestionError On PostBack Pinmembervijay.reddy5927-Jun-12 11:55 
SuggestionURL rewriting Pinmembersuhel8718-Apr-12 21:39 
GeneralMy vote of 4 Pinmembersuhel8718-Apr-12 21:37 
Questiondefault document SEO Pinmembercsgraham25-Jan-12 2:04 
AnswerRe: default document SEO PinmemberRichard Birkby25-Jan-12 2:22 
GeneralMy vote of 2 PinmemberUmair Aslam Bhatti15-Dec-11 18:33 
QuestionURL Rewrite in C#.NET PinmemberAleksandra Czajka18-Aug-11 13:52 
Generalgetting error of the application trust level Pinmemberkadamnayak3-Jan-11 7:18 
QuestionPlease advise on the error from this app (Description: HTTP 404) Pinmembernatzol11-Aug-10 6:20 
AnswerRe: Please advise on the error from this app (Description: HTTP 404) Pinmembermadhgari.rk6-Jan-11 1:03 
QuestionError while running on shared hosting Pinmembersudh10325-Apr-10 21:38 
Questionhow do I use 2 parameters? PinmemberEMILIO RAFAEL24-Apr-10 5:12 
QuestionImage Problems Pinmemberhaitham hamed housin26-Mar-10 4:49 
AnswerRe: Image Problems PinmemberBalwant_Singh15-Oct-10 6:13 
QuestionHow can I use it wih IIS7? PinmemberDarkness8017-Mar-10 7:36 
GeneralHi Can you give me the vb.net code PinmemberMember 42274735-Jan-10 22:12 
Questionhow to avoid case sensitive Pinmemberrafiq_22jmr28-Dec-09 2:07 
GeneralMy Vote of 5 Pinmemberf r i s c h3-Oct-09 0:51 
GeneralRe: My Vote of 5 PinmemberAlexTiffy12-Jan-10 1:26 
GeneralRegarding Url rewriting Article PinmemberMember 442566519-Aug-09 4:39 
GeneralHello PinmemberHtoo Myat31-Jul-09 18:24 
GeneralHi.. PinmemberMember 272372414-May-09 1:17 
GeneralRe: Hi.. Pinmembertstuerer8-Sep-09 0:27 
GeneralRe: Hi.. Pinmemberrafiq_22jmr28-Dec-09 2:13 
QuestionRewriting the Domain(URL) Pinmemberchalukiyan12-Apr-09 23:04 
Generalnice ideas Pinmemberbharnav13-Feb-09 6:10 
Questionneed help urgent please Pinmemberasmaqureshi82118-Feb-09 22:25 
QuestionRe: need help urgent please PinmemberMember 350106225-Mar-09 1:18 
did u found solution for yr issue?
i am running with same problem
Questionproblem Browsing Image on server and upload images on server. Pinmembersoft_jai17-Jan-09 1:34 
QuestionUrl Rewriting with Asp.net server control Pinmembersoft_jai30-Dec-08 20:18 
AnswerRe: Url Rewriting with Asp.net server control Pinmembersoft_jai5-Jan-09 2:31 
GeneralUrl Rewriting with Asp.net server control Pinmembersoft_jai30-Dec-08 3:27 
Generaliis 7 windows vista Pinmembersaikus17-Sep-08 12:34 
GeneralMessage Automatically Removed PinmemberDotNetGuts24-Jul-08 10:29 
Generalproblem with url rewrite PinmemberFadi Lteif27-Jun-08 11:03 
QuestionUrl Rewrite PinmemberJimBeam4-Feb-08 18:09 
GeneralUrl Rewriter Pinmemberpratap5574-Feb-08 2:40 
GeneralDon't work on IIS6 Pinmemberhakervytas14-Jan-08 21:43 
GeneralRe: Don't work on IIS6 Pinmemberdavidbarrett518874-Feb-08 10:05 
GeneralXSS Security issue with .RewritePath and Request.RawUrl PinmemberZombieBob18-Sep-07 11:06 
GeneralUpdated Version Pinmemberdnk.nitro13-Sep-07 0:29 
GeneralRe: Updated Version PinmemberRichard Birkby13-Sep-07 1:47 
QuestionSpecified cast is not valid Pinmembertiendung910_ntd30-Jun-07 19:36 
Questiongenerate assemby probem Pinmemberleyeg6-May-07 22:58 
GeneralITS Urgent Pinmembershhhhhhhhhh23-Apr-07 1:50 
Generalproblem in url rewriting Pinmembershhhhhhhhhh6-Apr-07 19:24 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 4 Jul 2002
Article Copyright 2002 by Richard Birkby
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid