ASP: mod_rewrite or URLRewrite with Classic ASP (Sorta)

Filed under: IIS, Quick Code — Written by Chrissy on Friday, April 28th, 2006 @ 8:01 pm

Using a Custom 404 error script in IIS makes it possible to emulate a very basic URL rewrite.

Sample Environment
- IIS 6
- Website domain: "www.me.com"
- URLRewrite directory: "code"

Steps
1. Create a file named rewrite.asp in the code directory.
2. Add a Custom Error for the 404 Not Found. Open up IIS -> Right click Website -> Properties -> Custom Errors -> 404,URL,"/code/rewrite.asp" or you can do it programatically:

Add custom 404 for a specific directory in a specific website.

<%
on error resume next
myDomain = "www.me.com"
myrewritedir = "code"
 
Set objW3SVC = GetObject("IIS://localhost/W3SVC")
For Each objSITE in objW3SVC
  If objSITE.class = "IIsWebServer" Then
 
      websiteNameArr = objSITE.ServerBindings
        for j = 0 to Ubound(websiteNameArr)
          websiteName = websiteNameArr(j)
 
           If instr(websiteName,myDomain) > 0 then
 
            Set objIISNewDir = GetObject("IIS://localhost/W3SVC/" & objSite.Name & "/root")
            Set CodeDir = objIISNewDir.Create("IIsWebDirectory",myrewritedir )
            CodeDir.SetInfo
            Set objIISNewDir = Nothing
 
            Set objIISRewriteRootDir = GetObject("IIS://localhost/W3SVC/" & objSite.Name & "/root/" & myrewritedir)
              CustomErrors = objIISRewriteRootDir.HttpErrors
              For i = 0 To UBound(CustomErrors)
                  If Left(CustomErrors(i),3) = "404" then
                      CustomErrors(i) = "404,*,URL,/" & myrewritedir & "/rewrite.asp"
                      objIISRewriteRootDir.HttpErrors = CustomErrors
                objIISRewriteRootDir.SetInfo
                      Exit For
                   End If
              Next
            Set objIISRewriteRootDir = Nothing
          End if
        Next
 
  End if
Next
%>

3. Copy and paste the following code into rewrite.asp

Rewrite Code

<%
'In IIS, 404 pages that are directed to an URL have the "error" URL attached in the query string.
'It looks something like this 404;http://www.me.com:80/code/nosuchfileblahblah1.asp
'We're gonna use it.. so grab it.
 
script = request.servervariables("QUERY_STRING")
if instr(script,"/") > 1 then
     myArray = split(script,"/")
       if instr(myArray(Ubound(myArray)),".asp") = 0 then
       myID = myArray(Ubound(myArray)) 'This is the method for obtaining the ID if you end your URL in the ID. Example: http://www.me.com/code/this-is-good-code/1
       else
       myID = replace(myArray(Ubound(myArray)),".asp","")  'This is the method for obtaining the ID if you end your URL in a fake extension. Example: http://www.me.com/code/this-is-good-code/1.asp
       end if
end if
 
'Now that you've extracted your code ID, just go about your business, you are done!
'Here's some sample code
 
if isNumeric(myID) then 'Make sure it's an ID and not some malicious code
response.write "The ID Extracted from the URL is: " & myID
else
response.redirect "http://www.me.com"
end if
%>

4. Call your tricked out webpage URI.

I installed a sample of this script @ netnerds.net. Click on the following URL to see the results: netnerds.net/code/example-in-the-house/1. You can also look around RealCajunRecipes.com. I use that code (heavily modified) in the recipes directory to make SEO friendly URLs. Woo!

33 Comments   -
  • Comment by Rick | July 16, 2006 @ 2:38 am

    Great how-to and very helpful. Thanks for sharing!

  • Pingback aspde seo - Webmaster Forumu | September 3, 2006 @ 12:38 am

    [...]

  • Comment by Martin Dan | October 25, 2006 @ 3:26 pm

    Can not make it work :(
    I dont get it .... my urls are 120% dynamic ex.

    http://www.me.com/default.asp?Action=Details&#38;Item=87

    If you can make it work .... and i can change the above to ex.:

    http://www.me.com/mytitletag_d_87.asp

    I whould love to pay for it...

    Best regards!

    Martin Dan

  • Comment by Chrissy | October 25, 2006 @ 5:12 pm

    Martin,
    At what point are you getting stuck? How familiar are you with VBSCript? Did you successfully setup the 404 page? In order to parse your URL, you can just do an instrrev until /, replace(".asp",""), urlArray = split(myurl,"_") to split your URL into an array at "_". Then urlArray(0) = Your title, urlArray(1) = Your action, urlArray(2) = the ID. one is your title, second is your action, third is your ID.

  • Comment by Rob Gaudet | October 31, 2006 @ 8:55 am

    Nice tip! Just when you thought you had found something in .net that could not be done in classic!

  • Comment by Neeru Khandelwal | January 9, 2007 @ 12:16 am

    This is a very good script work very good but I am not abel to set my error page dynamically
    hardly matters I did that manually

  • Comment by Dia | January 28, 2007 @ 11:07 pm

    hi,

    i successfully added a custom error page 404 for the site. and i can see the id extracted, but how to implement it with my site. specially, if i want my url http://www.idealviews.com/citywebhosting.asp?city=Mumbai to be something like this:
    http://www.idealviews.com/citywebhosting/city/Mumbai

    Your help will be very much useful.

    Thanks and regards,
    Dia

  • Comment by Sohnee | February 22, 2007 @ 11:27 am

    What is the Google impact of this method - using Apache's MOD_REWRITE or the .NET HttpApplication Rewrite will mean the URL with the friendly names is indexed by google.

    Will the custom 404 be treated as a 404 by Google or will it index the friendly name and all is well?

  • Comment by Chrissy | February 22, 2007 @ 4:50 pm

    Sohnee,
    The headers show up as 200 ..it's not a 404. I use it on RealCajunRecipes.com in both the categories and the recipes and Google has both of them indexed. You can also check the headers of the example page that I linked above.

  • Comment by Web Design Wrexham | March 1, 2007 @ 1:57 pm

    An excellent piece of scripting &#38; lateral thinking - Keep up the good work!

  • Comment by Tonto | April 17, 2007 @ 1:46 am

    Hi there... Thanks for this code it is good. I have a question though... When you get the ID number at the end, EG the 123 from: www.site.com/this-looks-nice/123 then what do you do... i have tried doing a response.redirect to the real page, EG: www.site.com/page.asp?id=123 but the URL in the address bar on my browser changes to this also... what do you lot do next? Thanks!

  • Comment by Chrissy | April 17, 2007 @ 1:58 am

    Tonto,
    You do not want to redirect it to the "real page" what you want to do is just incorporate that page within your "404" page. Instead of id = request.querystring("id") you will just use myID as extracted in rewrite.asp. Ie. you take the contents of page.asp and just put it in rewrite.asp

  • Comment by Tonto | April 18, 2007 @ 4:35 am

    Hi Chrissy...

    Thanks for your help... we are now starting to implement it on to our site! Check this out:

    http://www.ukdancerecords.com/vinyl-records/the-electric-press-tone-control-20-20-vision/vis148

    Lovely looking URL, even if i do say so myself...

    Thanks again for your help!

  • Comment by Allen McGuire | April 24, 2007 @ 9:56 am

    Thanks for the idea - never though to use an alternative landing page for my 404 errors. I personally wanted to use this to create Simple URLs for member bands - http://www.madtownlounge.com/supertuesdayband, for example (versus http://www.madtownlounge.com/members/profile.asp?id=83). So, instead of parsing out what you called myID, I parsed out the members personal portion of the URL (supertuesdayband), queried my database to ensure it was valid, then got the ID from that query. Everything else flowed as expected - with a few hiccups due to includes and such.

    Thanks for the idea!
    Allen

  • Comment by Tonto | April 25, 2007 @ 2:36 am

    Hi Guys...

    We've had a little problem with the URL rewrite... Wondering if anyone could help ;)
    Basically we've got it working fine, but, if the myID number doesnt exist, or someone tries to go to an old link on the site that doesnt exist anymore, we want it to display a message...

    What we did was this... We get the myID, then run an SQL statement to get all the info from the database... then after that we write 'if rs.eof is true...' and display our message... This isn't working! In fact we get this weird error message all the time, even if we remove that if statement... it always says theres an error at 'rewrite.asp line 0'.... Line 0? We're well confused...

    check this: http://www.ukdancerecords.com/oldlink.asp

    I don't suppose anyone knows the reason for this, or if there is another way of getting round it so we can display a custom message if the ID number doesnt exist....

    Any help would be greatly appreciated guys!

  • Comment by Mukesh sharma | May 22, 2007 @ 10:41 pm

    HI friends,

    I tried the above script but this is not working for me ...

    Can you please any of you give me step by stp explaination how to add the pages and how to configure the website...

    Thanks in advance

    Mukesh sharma

  • Comment by Mukesh sharma | May 24, 2007 @ 10:15 pm

    Hi all.. now this script is working for me but but i am facing the problem of session expiration... Can any of you help me..

    Thanks in advance...

    Regards,

    Mukesh sharma

  • Comment by Mukesh sharma | June 5, 2007 @ 8:52 pm

    HI friends i have use the above 404 url rewriting ... and that is working very fine for me except two problems..

    1. My site is responding very slow as compared to other sites (The reason may be of two requests first one for 404 page and then the actual page transfer.)

    2. on the live server my url turns to be
    http://d407183.av157.av1designs.net/code/rewrite.asp?404;http://d407183.av157.av1designs.net/Single-Rose-p-10.asp

    guys can anybody help me to find out the solution of above given two scenarios...

    Thanks in advance...

    Mukesh Sharma

  • Comment by Gary | June 7, 2007 @ 8:18 am

    Hi I was able to extract the ID, but now i am stuck. What do I do with the ID? How do I go from this to get my url rewritten?

    Thanks
    Gary

  • Comment by Uygar Yasar | July 15, 2007 @ 6:58 am

    This question, 'How can i rewrite pages in ASP?!?', was eating my mind; 'til see your demo. Great! Thanx.

  • Comment by Kulwant | October 15, 2007 @ 8:45 am

    I am not able to implement custom 404 page programmatically.

    any help on that will be appreciated.

  • Comment by John | December 26, 2007 @ 6:07 am

    I am too, it's not able to implement custom 404 page programmatically.

    any help on that will be appreciated.

  • Comment by dennis | February 26, 2008 @ 3:18 am

    Hi there, I was able to put up the custom 404 page but somehow, i still need to type in .asp in the url in order to extract myID.
    Eg, i need to type mydomain.com/123.asp instead of mydomain.com/123.
    If i just typed in 123 without .asp, myID return empty. Chrissy can you pls help me out? Or anyone pls... thanks alot in advance!

  • Pingback ASP Classic Programming Still Alive | March 28, 2008 @ 6:17 pm

    [...] Mod ASP Rewrite [...]

  • Comment by giselle | March 31, 2008 @ 1:47 am

    hello all, i have try to implement the code..but it seem not work for me..anyone can help me more? plz help..thank you. i m using pure asp and wana test in the locahost.

  • Comment by Surjit | April 19, 2008 @ 2:21 am

    Hi,
    How can i rewrite URL like subdomain.domainname.com for example
    http://www.mysite.com?userID=1 to http://www.username.mysite.com in classic ASP
    Can anyone help me.

    Thanks in advance

  • Comment by ibrahim | April 24, 2008 @ 3:16 am

    hi dear colleague.i read your article and i apply your code.run and take result.bu only reason i didn't make database sample(msaccess) so i you help me i'm glad to you

  • Comment by pranav shah | May 1, 2008 @ 3:00 am

    hello all, i have try to implement the code..i read your article and i apply your code.
    http://www.primetechsoftware.com

  • Comment by carl strouse | May 21, 2008 @ 2:56 pm

    this method is except i find following the log files much harder as requests are now reported as errors. how did you get around this? in the end i decided to go for a isapi filter to handle it. http://www.mediamodus.com/isapi-url-mod-rewrite-for-iis it works well although.

  • Comment by B. Kumar | June 5, 2008 @ 4:18 pm

    Hi Chrissy,

    pls help for

    URL rewrite: rewrite the URLs of the categories on this page to show the category name etc instead of numeric query strings. (This will help rank the category pages in search engines well).

    Thx
    B Kumar

  • Comment by Raja. R.K | July 14, 2008 @ 2:48 am

    Hi,

    If I want to rewrite URLs like:

    http://www.mysite.com/city.asp?state=California&city=Compton
    to
    http://www.home-security123.com/geo/Security-System-Offers/California/Compton

    how can I rewrite this URL to make it friendly?...

  • Comment by Chris | September 18, 2008 @ 7:55 am

    i hate the fact that you cant use mod_rewrite or something similar with asp! why is microsoft not implementing this into their server technology? apache rules for this reason as well as many others, apache rules IIS sucks! lol though i do code for both! :D lol

  • Comment by Kevin | October 3, 2008 @ 1:48 am

    Hi Raja,

    I used carls suggestion, check out http://www.mediamodus.com/isapi-url-mod-rewrite-for-iis it worked for me.

Leave your comment