Scott on Writing

Musings on technical writing...

URL Rewriting in ASP.NET

My latest MSDN article has been published, URL Rewriting in ASP.NET.  This article looks at how to use either HTTP handlers or HTTP modules to perform URL rewriting in the ASP.NET HTTP pipeline.  URL rewriting is the act of taking an incoming URL and seemlessly changing it to a different one.  For example, you might have a page that lists products from different categories using a URL like /ListProducts.aspx?CategoryID=XXX.  However, you might want to provide a more user-friendly URL, like /Products/Meat.aspx, and /Products/Dairy.aspx.  URL rewriting is intercepting a request to, say, /Products/Dairy.aspx, and mapping it to the actual page, /ListProducts.aspx?CategoryID=XXX.  The benefit is that the user can enter a friendly, memorable URL, while you can still use the less-user-friendly URLs with complicated querystring values.

If you have done any significant examination of URL rewriting in ASP.NET you've likely noticed that URL rewriting isn't really that easy to implement.  There are a number of “gotchas,” like URL rewriting evaporating when using postbacks; or URL rewriting not playing nicely with forms authentication.  This article addresses many of these subtlties.

[UPDATE 2005-10-26: Fixed URL to article (was broken)]

posted on Thursday, March 18, 2004 9:36 AM

Feedback

# re: URL Rewriting in ASP.NET 3/18/2004 10:46 AM Ian Leff

Hi Scott,

Awesome article as usual. On one of my sites I'm using some really yucky urls: http://www.easyblog.com/blog.asp?nick=ileff

(never mind the page is legacy asp, im migrating it)

What I would like is http://ileff.easyblog.com is that possible with url rewriting?

With my initial experiments it seems that subdomains need to be setup at my registrar's name server so that doesnt seem practical to automate.

thanks,

ian

# re: URL Rewriting in ASP.NET 3/18/2004 10:58 AM Scott Mitchell

Ian, what you are after needs to be setup with your Web hosting provider. They need to configure the Web server to map ileff.easyblog.com to www.easyblog.com/blog.asp?nick=ileff. I am not very familiar with the precise steps needed for this, unfortunately.

# re: URL Rewriting in ASP.NET 3/18/2004 11:36 AM Mike Schinkel

I think clean URLs are extremely important and I plan to blog about the topic someday. Have you not found a way convert: /Products/Meat/
into: /ListProducts.aspx?CategoryID=XXX without requiring a /Meat/ subdir and Default.aspx file? That's the problem I really want to solve.

# re: URL Rewriting in ASP.NET 3/18/2004 3:13 PM Ian

Thanks Scott,

I am my own Web Hosting provider, IIS in the kids playroom closet ;)

I think where I fall short is I dont own and control my own name servers. I use register.com name servers.

If I come up with the right info I'll forward it to you. Thanks for all the hard work, Scott on Writing is my favorite rss feed!

# re: URL Rewriting in ASP.NET 3/18/2004 10:17 PM Scott Mitchell

Ian, I talked to Steve Schofield [http://weblogs.asp.net/steveschofield/], who shared the following with me on setting up blah.yourdomain.com:

create an A record in DNS called blah.domain.com pointing the IP address you
want (this will be your host header used in IIS)
Create a directory in windows where the files are going
C:\Inetpub\Blah.domain.com_root\
open internet information services MMC in windows (under Administrative
Tools)\
Expand out till you see websites
Right click New website
next
Type in description
Next
in the textbox, type in host header you put in DNS
Next
Type the path you created for the content
finish.

# re: URL Rewriting in ASP.NET 3/19/2004 11:25 AM Steve Schofield

great article on URL Rewriting, this seems a lot easier than using apache mod_rewrite. Have you any experience using apache mod_rewrite module?

# re: URL Rewriting in ASP.NET 3/20/2004 12:22 PM Scott Mitchell

Steve, I've read up on mod_rewrite, but never used it myself, no.

Thanks.

# re: URL Rewriting in ASP.NET 3/21/2004 12:08 AM Richard Murillo

This post was most very helpful. I've already started integrating it into a solution for an ecommerce site instead of passing around real nasty id numbers for categories and products. Thanks a ton!

# re: URL Rewriting in ASP.NET 3/21/2004 4:46 PM Steve J Rodgers

I wonder which came first: the msdn article or the blog?
http://www.interact-sw.co.uk/iangblog/2004/01/12/shinyurl

# re: URL Rewriting in ASP.NET 3/21/2004 5:41 PM Scott Mitchell

Steve, there are TONS of blog entries, articles, and FAQs about URL rewriting in ASP.NET, ones that appeared prior to the URL rewriting article of mine on MSDN. Here are a few:

URL Rewriting with ASP.NET
http://www.codeproject.com/aspnet/URLRewriter.asp

Rewrite.NET - A URL Rewriter for .NET
http://www.15seconds.com/issue/030522.htm


And others (many blog entries). One thing I have noticed is that there is a set of people that believe, "If some topic X has been written about before, no one else should ever write about X." I find this belief silly for a number of reasons:

1.) The "worth" of a piece of information is due in large part to how it's presented. Alice might find the methods I use to describe URL rewriting much clearer than someone else writing about the same topic. In a similar vein, Bob might find my techniques confusing, but readily understand the writings of another.

2.) It doesn't make economic sense. Well, at least not for anyone but the first author.

3.) Even if ten people write on one particular topic, none of the ten people are going to write precisely the same thing. That is, there's information to gain from each person's interpretation and explanation that's not present in others.

# Writting on topics that have already been covered 3/22/2004 8:41 AM Rj

I would just like to agree with what you've just said, I find several articles on the same topic helpful, as each article is a different perspective and approach on the same subject. I find your writting very accessible, I'd personal hope you write about every topic, including baseball and home mortgage loans.

# re: URL Rewriting in ASP.NET 3/23/2004 12:26 AM Oleg

I have two solutions for this problem:

1. For server under my control - ISAPI filter which forwards requests to ASP.NET passing url in headers.

2. For server at Internet hosting provider - pointing 404 error handler to ASP.NET page. It has some drawbacks like engine not properly setting Request.Method to POST - it always GET but with POST variables set. So you need to manually read it.

This solutions work for paths like /news/ without creating empty folders containing default.aspx.

# re: URL Rewriting in ASP.NET 3/23/2004 12:59 PM Steve Ellis

I'm curious if you have any thoughts or experience on the URL rewriting topic when it comes to implementing the Front Controller pattern in ASP.NET?

Thanks
-SE

# re: URL Rewriting in ASP.NET 3/24/2004 11:56 PM Nasseam Elkarra

I am currently working on my blog engine with URL Rewriting support and I implemented it as an HttpModule and used wildcard mapping to send all requests to ASP.NET which solves the problem of needing a directory structure and Default.aspx files to handle non-ASP.NET requests. I process requests that match my rule list and simply ignore everything else. I haven't found any problems using this method so far. In terms of performance, an if statement won't kill you.

# re: URL Rewriting in ASP.NET 3/25/2004 8:40 AM Mark Dicken

Scott Mitchell,

Firstly Great article on MSDN. Keep them coming...

You last comment was :- "you have to either create mock directories and Default.aspx pages, or configure IIS so that all incoming requests are blindly routed to the ASP.NET engine."

1) Please can you advise me or point me in the right direction on how to 'configure IIS so that all incoming requests are blindly routed to the ASP.NET engine.' ???

2) I want a 'person to be able to enter a URL that might not actually exist' but without the headache of creating 'mock directories and Default.aspx pages' what are my alternative options ???

... Basically I'm after a simple solution that simply evaluates each and every request, with each request I want to evaluate the requested web page full URL request as you stated in the article have Truly "Hackable" URLs...

...Surely I'm not asking too much (from Microsoft ASP.NET) ??? (or am I) ???

If it helps I can give a clear example of what I am trying to achieve...

From searching around it sounds you one of the most knowledgeable people in this area - I hope you have the time to reply.

Thanks In Advance.

Regards

Mark Dicken
email@MarkDicken.com
http://www.MarkDicken.com

# re: URL Rewriting in ASP.NET 3/25/2004 9:08 AM Scott Mitchell

Mark, you can find how to map all incoming requests to IIS at:
http://scottwater.com/blog/archive/2003/06/25/7845.aspx


Essentially, the .Text blog engine can be configured in this manner. There's more discussion at the .Text Wiki, IIRC.
http://dottextwiki.scottwater.com/

Also, you could ask on the .Text forum at the ASP.NET forums:
http://asp.net/Forums/ShowForum.aspx?tabindex=1&ForumID=149

# re: URL Rewriting in ASP.NET 3/26/2004 1:12 AM Mark Dicken

Scott,

Thanks for the pointer but the sceen shot is different. It looks like IIS has this facility in win2k3. I'm currently using IIS with win2k and I think the following hack does a similar job http://www.stargeek.com/item/8132.html, I'm hoping I can map * and not .*

Regards
Mark Dicken


# re: URL Rewriting in ASP.NET 3/27/2004 9:29 PM Mike Schinkel

Scott>> You can find how to map all incoming requests to IIS at:...

When I've tried that it seems to require an actual ASPX page, i.e. default pages quit working. Have you found with your techniques you can get Default pages to work too?

# re: URL Rewriting in ASP.NET 3/28/2004 10:56 AM Mark Dicken

Mike,

Yes your right my default.aspx pages STOPPED WORKING!!!, I'm still after a solution. Actually ALL I'm after is a working sample of some kind that I can tweek for my own exact requirements... I was actuallt thinking of emailing 'StarGeek' if they have an example... Does anyone have a simple (and working!) example ... ???

Regards

Mark Dicken
http://www.MarkDicken.com

# re: URL Rewriting in ASP.NET 3/28/2004 1:15 PM Stephen Vanterpool

The problem i am having is that while the page loads, all the other content has stopped working. (Images,css, etc..) They are relative paths (as i would like them to remain). When i open the page in the browser, the images are all based off the virtual path instead of the actual root of the app. Any Ideas?

# re: URL Rewriting in ASP.NET 3/28/2004 3:20 PM Scott Mitchell

Mike/Mark/Stephen:

I discuss some of these issues you have, and how to learn more at http://scottonwriting.net/sowblog/posts/943.aspx.

Hope this newer blog entry helps y'all.

# re: URL Rewriting in ASP.NET 3/31/2004 7:36 AM Mark Davidson

Scott,

Great article, but I noticed one big omission. How does URL Rewriting affect log files depending on the method chosen (ISAPI or HTTP Module or HTTP Handler). I don't know if you have any insight into this, but if you do it would be appreciated.

# re: URL Rewriting in ASP.NET 3/31/2004 8:42 AM Scott Mitchell

Mark, I'll do a little research on this when I have time, but I'm fairly certain that how it works is that IIS does its logging as the request comes in. So if a request is made for /Products/Meat.aspx, that's what gets recorded, even though that file may not exist and URL rewriting at the ASP.NET level might be employed to rewrite the user to /ListProductsByCategory.aspx?CatID=XXX. Now, if you employe ISAPI URL rewriting, I'm not certain if the logging happens before or after the rewriting.

# re: URL Rewriting in ASP.NET 4/7/2004 6:50 AM Tony Steele

Great Article.

Have you tried writing the domain, as well as friendlier urls I want to change the domain. For example on our websites I would like to redirect www.chisickw4.com/forum/new.aspx
to www.nnet-server.com/server/app/forum/new_message.aspx.

Do you know if there an consequences as far as sessions and cookies if I did this. For instance would the www.nnet-server.com get the www.chisickw4.com cookie ?

# problem in URL Rewriting in ASP.NET when host on ISP 4/27/2004 9:59 PM sandeep pandit

hello sir,
i read your article on URL rewriting in asp.net on msdn.i have also used the same in my project.URL rewriting is working fine in our LAN and on our configured IP but problem is that when we host our site to some ISP its not working and giving error like this "THE PAGE CAN NOT BE FOUND" its really emberrasing because i am not able to find out the proble any where
i am seding the code which i am using
Sample code
==================
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires at the beginning of each request
Dim context As HttpContext
context = HttpContext.Current()
Dim strOldPath As String
strOldPath = Trim(context.Request.Path.ToLower())
Dim strToken As String
strToken = "accomodationdetail"
Dim intI As Integer
intI = strOldPath.IndexOf(strToken)
Dim intLen As Integer
intLen = strToken.Length
Dim intJ As Integer
If intI <> -1 Then
intJ = strOldPath.IndexOf(".aspx")
If intJ <> -1 Then
Dim strDetail As String
strDetail = strOldPath.Substring(intI + intLen, intJ - (intI + intLen))
Dim strNewPath As String
strNewPath = strOldPath.Replace(strToken + strDetail + ".aspx", "AccomodationDetail.aspx?intID=" & strDetail)
context.RewritePath(strNewPath)
End If
End If
end sub
============================
above code is doing fine in our lan and on our configured IP
but when i called some page like this

/accomodation/accomodationdetail22.aspx
its not working
i think you got my problem
please help me as soon as possible
thanks
regards
sandeep

--
Open WebMail Project (http://openwebmail.org)

# re: URL Rewriting in ASP.NET 6/24/2004 8:44 AM LastKnight

I wrote a little article about what happened to me playing with UrlRewrite and old-style ASP CMS...
Basically I started trying to use UrlRewrite and ended with a all-pourpose all-language Url Rewriting and Caching engine. Funny ;)

The article is at :
http://www.lastknight.com/DotNet-Url-Rewriting-and-Caching-Engine.aspx

# re: URL Rewriting in ASP.NET 8/30/2004 2:07 PM Roger

Great article. I'm using the code from the MSDN link and you have saved me at least 1 weeks work. I have a question on registering the HttpModule in web.config. My application is as follows: main web site c:/inetpub/wwwroot/spl/ maps to http://localhost/ and admin site c:/inetpub/wwwroot/spl/admin/ map to http://localhost/admin/.
I added the HttpModule line in the web.config at c:/inetpub/wwwroot/spl/... so when i go to a page within, http://localhost/admin/ why does it look for the HttpModule when I have a different web.config in c:/inetpub/wwwroot/spl/admin/?

# re: URL Rewriting in ASP.NET 8/30/2004 2:17 PM Scott Mitchell

Web.config files are applied hierarchically. That is, if you have a Web.config registering an HTTP Module in one directory, the subdirectories will also use that Module. To disable this, use the <remove> element to remove the HTTP Module from the child directory.

# re: URL Rewriting in ASP.NET 8/30/2004 3:21 PM Roger

Thanks for the tip. However, I cannot seem to get it to work... I added the folloing snippet to my web.config @ http://localhost/admin/">http://localhost/admin/:
<httpModules>
<remove name="ModuleRewriter"/></httpModules> and when I go to a page within http://localhost/admin/">http://localhost/admin/, it's still looking for the HttpModule. Any ideas?

# re: URL Rewriting in ASP.NET 11/26/2004 4:44 AM Martin Hinshelwood


I am trying to get IIS6 to map all requests to the ASP.NET engine, but when I try to map the extention * or *.* I get a wee popup bubble that sais that it is not valid!

How do you set IIS on Windows 2003 to map all requests to ASP.NET?

Marv

# ERROR: The resource cannot be found. Urgent help needed. 8/26/2005 7:32 AM Will

Tried your code and it seems to be parsing correctly but I get this error:

The resource cannot be found.
Requested Url: /movies/star.aspx

My rewrite rule is:

<RewriterRule>
<LookFor>~/star/([\w]+).aspx</LookFor>
<SendTo>~star.aspx?folder={$1}</SendTo>
</RewriterRule>

I have a dummy star folder containing default.aspx.

I'm running this on my local server and directly calling the URL http://localhost/movies/star.aspx?folder=Denzel works perfectly but when i call http://localhost/movies/star/Denzel.aspx I get this error.

Any ideas? Urgent help needed.

# re: URL Rewriting in ASP.NET 8/26/2005 9:15 PM Nguyen Le Thanh

I want get config from another file(ex: rewrite.config) not web.config. Please

# re: URL Rewriting in ASP.NET 10/13/2005 2:12 PM Stef

Hey there,

I'm using your code for my portal software.
It works all well on my localhost, but when I upload the site to my server, and go to the first page, I got an error like:
String cannot be of zero length. Parameter name: oldValue
Anyone has a suggestion where to look?
Thanks
Stef

# re: URL Rewriting in ASP.NET 10/20/2005 7:20 PM MP

How do you intend to handle response.redirect.
For eg. if my page is test.aspx and i want user to see abc.aspx but i dont want to write
Response.Redirect("abc.aspx");

# re: URL Rewriting in ASP.NET 10/26/2005 10:59 AM steve bushman

Looks like the link to the MSDN article is broken...

# re: URL Rewriting in ASP.NET 10/26/2005 11:04 AM Scott Mitchell

Steve, thanks for the heads up, the link has been fixed. FYI, the correct, working link is now:
http://msdn.microsoft.com/library/en-us/dnaspp/html/urlrewriting.asp

Thanks again for the watchful eye.

# re: URL Rewriting in ASP.NET 6/5/2006 5:55 AM Nimit

Steve, Can I apply dummy(false) domain name by using url rewriting in asp.net?
For example,

real url : www.nimit.com/personal.aspx
dummy domain : www.friend.com/friend1.aspx

From
Nimit patel
nimit_104@yahoo.com

# re: URL Rewriting in ASP.NET 10/8/2006 6:55 PM Kheang

Scott.

Not sure if my last message was posted, but does this work for 2.0.

I keep getting secruity exception errors because my web hosting co has tight security in place.

let me know.

thanks

# re: URL Rewriting in ASP.NET 2/5/2008 10:42 PM Rakesh Mangroliya

Hi,
Scott,
I have one Problem in URL rewriting.
My web site use Forms Authentication.so,when any URL access of location tag.meance authentication to role.at that time it redirect to login page with ReturnURL in QueryString Parameter with actuall URL.
so what should we do ?

# Re: Request for feature 6/1/2008 11:53 AM Channel 9

Ah.. URL Rewriting!

# Re: Request for feature 6/1/2008 11:53 AM Channel 9

Title:  
Name:  
Url:
Protected by Clearscreen.SharpHIPEnter the code you see:
Comments   

My Links

Ads Via DevMavens

Archives

Post Categories

 

I am a Microsoft MVP for ASP.NET.
I am an ASPInsider.
<March 2010>
SMTWTFS
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

Comment Stats

DayTotal% of Total
Sunday 2056.8%
Monday 42514.1%
Tuesday 51917.2%
Wednesday 55618.4%
Thursday 58019.2%
Friday 54718.1%
Saturday 1886.2%
Total 3020100.0%

Hour1Total% of Total
12:00 AM 782.6%
1:00 AM 812.7%
2:00 AM 682.3%
3:00 AM 822.7%
4:00 AM 692.3%
5:00 AM 1264.2%
6:00 AM 1193.9%
7:00 AM 1816.0%
8:00 AM 1926.4%
9:00 AM 1585.2%
10:00 AM 1886.2%
11:00 AM 1936.4%
12:00 PM 2016.7%
1:00 PM 1846.1%
2:00 PM 1695.6%
3:00 PM 1354.5%
4:00 PM 1153.8%
5:00 PM 1073.5%
6:00 PM 1013.3%
7:00 PM 1073.5%
8:00 PM 923.0%
9:00 PM 882.9%
10:00 PM 913.0%
11:00 PM 953.1%
Total 3020100.0%

Comments by Blog Entry Date/Time

Day Entry MadeAvg.Total
Sunday 5.00160
Monday 4.80384
Tuesday 4.04477
Wednesday 7.39680
Thursday 6.26676
Friday 5.07466
Saturday 4.78177
Total 5.403020

Hour1 Entry MadeAvg.Total
12:00 AM 5.2937
1:00 AM 1.002
5:00 AM 0.000
7:00 AM 3.8550
8:00 AM 3.72134
9:00 AM 6.06297
10:00 AM 5.63276
11:00 AM 4.22194
12:00 PM 6.16351
1:00 PM 3.09133
2:00 PM 4.89230
3:00 PM 7.67322
4:00 PM 4.00108
5:00 PM 6.07170
6:00 PM 4.64116
7:00 PM 8.95188
8:00 PM 8.63164
9:00 PM 5.00115
10:00 PM 6.31101
11:00 PM 4.5732
Total 5.403020

Learn More About Comment Stats
1 - All times GMT -8...


Blog Stats

Favorite Web Sites

My Books

My MSDN Articles