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:


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


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 Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, holds a master's degree in Systems Engineering and is coauthor of Learn dbatools in a Month of Lunches. Chrissy is certified in SQL Server, Linux, SharePoint and network security. You can follow her on Twitter at @cl.

Posted in IIS