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: "" - 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:

<% on error resume next myDomain = "" 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

<% '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; '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: 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: 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 "" end if %>

4. Call your tricked out webpage URI.

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