ASP: mod_rewrite or URLRewrite with Classic ASP (Sorta)

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!

Chrissy is a PowerShell MVP who has worked in IT for nearly 20 years, and currently serves as a Sr. Database Engineer in Belgium. Always an avid scripter, she attended the Monad session at Microsoft’s Professional Developers Conference in Los Angeles back in 2005 and has worked and played with PowerShell ever since. Chrissy is currently pursuing an MS in Systems Engineering at Regis University and helps maintain RealCajunRecipes.com in her spare time. She holds a number of certifications, including those relating to SQL Server, SuSE Linux, SharePoint and network security. She recently became co-lead of the SQL PASS PowerShell Virtual Chapter. You can follow her on Twitter at @cl.

Posted in IIS
50 comments on “ASP: mod_rewrite or URLRewrite with Classic ASP (Sorta)
  1. Rick says:

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

  2. Martin Dan says:

    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

  3. Chrissy says:

    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.

  4. Rob Gaudet says:

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

  5. 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

  6. Dia says:

    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

  7. Sohnee says:

    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?

  8. Chrissy says:

    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.

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

  10. Tonto says:

    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: http://www.site.com/this-looks-nice/123 then what do you do… i have tried doing a response.redirect to the real page, EG: http://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!

  11. Chrissy says:

    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

  12. Tonto says:

    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!

  13. 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

  14. Tonto says:

    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!

  15. 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

  16. 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

  17. 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

  18. Gary says:

    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

  19. Uygar Yasar says:

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

  20. Kulwant says:

    I am not able to implement custom 404 page programmatically.

    any help on that will be appreciated.

  21. John says:

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

    any help on that will be appreciated.

  22. dennis says:

    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!

  23. giselle says:

    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.

  24. Surjit says:

    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

  25. ibrahim says:

    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

  26. pranav shah says:

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

  27. carl strouse says:

    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.

  28. B. Kumar says:

    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

  29. Chris says:

    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

  30. Kevin says:

    Hi Raja,

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

  31. Binu says:

    Thanks, its really useful.
    Will IIS7 will support this.

  32. meds says:

    i’t will agreat if I can implement this code. thanks for the code, iI want test on my server.

  33. Manoj Kumar says:

    Hi Chrissy,

    Is there any way by which we can force all files or files with certain extensions in a particular directory to parse through a authentication.asp file

    For example if is have a directory download which has .doc and .pdf files, can’t I configure server like if anyone try to access abc.pdf file, he will be redirected to authentication.asp file

    Thanks

  34. dunks says:

    i read your article and i apply your code.Thanks

  35. Suraj jain says:

    <%
    ‘URL Rewrite using 404 page made simple
    ‘incase if u r looking for a script which can collect data from url and build your own formatted url.
    ‘then this script will do it
    ‘in the below example i assume that… url used will be this

    ‘http://www.xyz.com/module/actual_asp_page/pass_title_here/querystring_fld_name/querystring_fld_value

    ‘in case if u dont understand the above.. see the below url

    ‘http://www.mysite.com/forum/display/How-get-listed-on-google/msg_id/744

    ‘You can easily modify the script to adjust the number of variables passed
    ‘ mail me your comments at [email protected]

    ‘gets http host from server variable.
    HTTP_host=Request.ServerVariables(“HTTP_host”)

    ‘get all query string values
    script = request.servervariables(“QUERY_STRING”)

    ‘now we need to clean up the query string by replace 404 error code and remove http_host too
    script=replace(script,”404;http://“&HTTP_host&”:80/”,””)

    ‘now time to split the data into array
    myarray=split(script,”/”)

    ‘check if the url is proper or else redirect to http_host aka default page of the site
    if not UBound(MyArray)

  36. Suraj jain says:

    ‘cont from prev post

    ‘get values from array and build url which u wish to redirect
    Response.redirect “http://”&HTTP_host&”/”&myArray(0)&”/”&myArray(1)&”.asp?”&myArray(3)&”=”&myArray(4)
    else
    ‘incase url is not proper than the user will redirect to default page of the site
    response.redirect “http://”&HTTP_host
    end if

    %>

  37. yazgunu says:

    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

  38. I used carls suggestion, check out

  39. V2Media says:

    You can give me an example so that when it works, give accurate results is not.

    thanks much

  40. MAK says:

    would 404 rewriting affect google or search engins ranking and SEO?

  41. Trey says:

    u’re link funny enuff is giving a 404 )
    http://netnerds.net/code/example-in-the-house/1
    anywhee else to grab the full example and am i pushing it requesting c#

  42. Chrissy says:

    Hah oops. I migrated that webserver and forgot to enable that directory to accept the 404. I’ll get around to it one day ;)

  43. tank says:

    im new to asp and i really don’t get it. I made error page, but how do i change my link on my listview so it wont show: mypage?Idproduct=111???
    Is there a script to download?
    sorry but i just don’t know how to make it work with my estore – candypress

  44. Ash says:

    Hi Chrissy
    i m do like that (Custom Errors -> 404,URL,”/code/rewrite.asp”) but i want to this by set custom error page by programatically.
    Please tell me

    Thanks

  45. ika says:

    hello,
    how about my hosting in shared webhosting ,
    i think i cannot configure/implement this script on my shared webhosting :
    ————-
    Set objIISNewDir = GetObject(“IIS://localhost/W3SVC/” & objSite.Name & “/root”)
    Set CodeDir = objIISNewDir.Create(“IIsWebDirectory”,myrewritedir )
    ————-

    do you any ideas for share webhosting.
    also i cannot install isapi module for my website :(
    please help
    thanks

  46. Jun says:

    If i have alot of ids to pass on??
    for example, http://www.abc.com/test.asp?id=1&id2=2&id

  47. YouVic says:

    Is there a step by step? I am really new at ASP, but I could learn very easily. My issue is, I have got rewrite.asp setup, but it is not doing anything. Do we need to change any variables in the code itself, or is it just a CopyPasta?

  48. Wesley says:

    Hi Chrissy,

    I did all step but it seem doesn’t work. could you tell me how to set in IIS 7 please?
    I probably did something wrong in this step.

    I created rewrite.asp file in my code folder already in localhost.
    What else i need to create?

    Thanks,

  49. Jaffer says:

    can any one help me how to change the url as below

    from : domain/index.asp

    to: domain/index

4 Pings/Trackbacks for "ASP: mod_rewrite or URLRewrite with Classic ASP (Sorta)"

Leave a Reply

Your email address will not be published. Required fields are marked *

*