URL Rewriting in Classic ASP

By · July 30, 2007 · 36 comments

What is URL rewriting?

URL rewriting is usually used to make a URL for a dynamic web page more presentable, either for the reader or for search engines.

For example, a regular Classic ASP URL might look like this:

A more presentable way of rewriting the URL might be:

It used to be that search engines would not index pages with querystrings (the information after the .asp? in the URL). These days this is not the case and most search engines do index these types of pages. However, it has been suggested that major search engines might not be able to use more than three querystring parameters.

Also many search engines do look for keywords in the URL, but probably not in the querystring.

If you can remove the querystring altogether then you may stand a better chance with the search engines.

How to do URL rewriting in Classic ASP?

Unfortunately Classic ASP can't usually recognize URLs like this unless you happen to create static pages in each location.

For dynamic database-driven pages the simplest solution is to use an ISAPI filter but these cannot not always be installed, depending on your web host.

There are a couple of methods that can be used to do this in Classic ASP without installing additional components.

URL redirection in ASP using custom error pages
If you are able to set up custom error pages then you can create an error page that can translate these rewritten URLs and transfer to the correct page.

For a relatively simple to implement example of this:

Use the following script in your custom error page:

strQuery = Request.ServerVariables("QUERY_STRING")
strPage = Mid(strQuery, InStrRev(strQuery, "/") + 1)

' Change page.asp and page2.asp and add duplicate lines for
' each page you want redirection
If strPage = "page.asp" Then
Response.Status="200 OK"
ElseIf strPage = "page2.asp" Then
Response.Status="200 OK"
'Put your normal error page here
End If
You need to modify it a little. Change all of the page.asp and page2.asp to your own page names and add more of these lines if necessary. And add a custom error message after the Else line so that normal errors are still display when needed.

Add the following function to the beginning of each of your scripts that will use URL redirection:

Function RequestQS(strParam)
strQuery = Request.ServerVariables("QUERY_STRING")
lngStart = InStr(strQuery,"/" & strParam & "/")
RequestQS = ""
If lngStart > 0 Then
lngStart = lngStart + Len("/" & strParam & "/")
lngEnd = InStr(lngStart + 0, strQuery, "/")
If lngEnd > 0 Then
RequestQS = Mid(strQuery, lngStart, lngEnd - lngStart)
End If
End If
End Function
Then in your scripts, instead of using the usual request/request.querystring/etc to retrieve your paramaters, use RequestQS(param-name).

When calling the page use the following format:
You can then request the values of param1name, param2name etc by using RequestQS. (NB. You can include as many parameters as you need.)

This example lacks any protection against characters that might cause problems in directory names. If the parameter had a / (forward slash) in it then it will cause problems. You are best to pass only text or numbers and perhaps a few other symbols like the minus sign. This may require additional functions to convert then reconvert unwanted characters.

A few negatives to using custom error pages have been suggested. One is that the error may be logged so if you are using this method your error logs may be huge. Another is that this may take up extra server processing time but I personally doubt there would be a significant difference.

URL redirection in ASP using subdomains

Another interesting possibility, for which I am not sure of the consequences to search engines, is using subdomains to store parameters. This eliminates the need to use custom error pages and puts keywords into the subdomain which may be treated as more important than directories by some search engines.

For example, using the sample example URL as above:

A more presentable way of rewriting the URL using subdomains might be:

This, of course, would depend on whether your hosting company allowed wildcard subdomains.

Here is an example of simple subdomain URL rewriting:

strServer = lcase(Request.ServerVariables("SERVER_NAME"))
' Change mydomain.com to your domain name and duplicate
' this line for additional domain names
strServer = Replace(strServer, "mydomain.com", "")
If strServer = "" Then strServer = "."
strParams = Split(strServer, ".")

Function RequestSD(intParam)
If intParam > UBound(strParams) Then
RequestSD = ""
RequestSD = strParams(intParam)
End If
End Function
You need to add (or include) this to the beginning of each script that you want to use the subdomain(s) as parameters. Make sure you change mydomain.com to your own domain name (don't include any http:// or www.) and duplicate the line for any additional domain names that might also be used.

Then to retrieve parameters use the RequestSD(parameter_number) function. For example, use RequestSD(0) for the first parameter, RequestSD(1) for the second and so on.

This example also lacks any protection against characters that might cause problems. If the parameter had a . (full stop) or a / (forward slash) in it then it will cause problems. You are best to pass only text or numbers and perhaps a few other symbols like the minus sign.

Update: There are now other ways to do this that might be simpler, for example the IIS7 URL Rewrite Module. However, the custom error page option can possibly give you more control.

Get the latest posts delivered to your inbox.

Comments (36)

# Posted by kumar · August 11, 2007

Above example is very useful whenever we change in custom error page.But i want without change the custom error page how to re write the url in classic asp.
Please send reply to me.
My email id : akumar8.k@gmail.com



# Posted by John Avis · August 14, 2007

I don't believe there is any way to do this without either a custom error page or ISAPI filter. The subdomain example above will work without custom error pages but does require that wild card subdomains be allowed.


John Avis
# Posted by Sumair · February 8, 2008

i tried your script , it worked fine , url was rewritten , but no image is displayed,

for example : my previous url was www.mysite.com/test.asp?year=new, it was rewritten to www.mysite.com/new/test.asp but the images are using path /new/image/test_image.jpg , where new folder doesnot exsist


# Posted by John Avis · February 8, 2008

Good point, Sumair! When using these techniques you must reference your image and link urls differently. If using relative urls you need to include the entire path so that no matter whether the page was reached through redirection or through it's normal address your images and links will be correct. In your example your image path should set to be '/image/test_image.jpg'.


John Avis
# Posted by Tom · March 17, 2008


Great article! URL rewriting is working precisely as planned with one hitch. After the server transfer occurs it seems like there is an encoding problem with the page content because some times there are funny symbols scattered around on the page. If I go directly to the page without the rewriting everything looks fine.

Any ideas?




# Posted by John Avis · March 17, 2008

Hi Tom. I haven't seen that before. Have you got a link or source that I can look at? You can contact me directly via the "Contact me" link at the top of the page.


John Avis
# Posted by Nikolet · March 19, 2008

Nice site!


# Posted by John - mypubspace.com · March 31, 2008

hi John, thanks for this, I am trying to get it to work at: www.mypubspace.com/error.asp

but it won't work?! am i doing it ok?!



# Posted by John - mypubspace.com · March 31, 2008

Hi John, thanks for this, my page is not working?!

have i done everything right?

and do i call a page like this?



# Posted by Surjit · April 19, 2008

Hi John,
Can you please explain me more about "URL redirection in ASP using subdomains" i am not be able to impelement.

Thanks in advance


# Posted by carl strous · May 21, 2008

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.


# Posted by Mark · July 10, 2008

Have tried this out but unable to make the not_found.html redirect to the asp page. Can you have not_found.html with a vbscript within head or does it have to be an asp page eg not_found.asp



# Posted by John Avis · October 16, 2008

Here is another similar method sent to me by a reader:

1) Make custom 404 page containing the following:
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
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
if isNumeric(myID) then 'Make sure it's an ID and not some malicious code
Response.Status = "200 OK"
response.redirect "/404.htm"
end if

2)In "newpage.asp", retrieve your URL variable:

<% myID = Right(Request.ServerVariables("HTTP_X_ORIGINAL_URL"),2) %>

This will only work for 2 characters but I'm sure you could write a script to collect all characters up to the "/".


John Avis
# Posted by Diggo · October 29, 2008

Thanks a lot, dude :)


# Posted by Jacob · December 17, 2008

Really helpfulThis Is By Far One Of The Best Sites


# Posted by Pooh · January 16, 2009

i call page www.mysite.com/year/new/test.asp
year is ParamName,new is ParamValue
result of page test.asp is correct
but Url : www.mysite.com/year/new/test.asp

what should i do.


# Posted by John Avis · January 16, 2009


Try calling your page with a url like this:


(You need to include the ParamName as well as the ParamValue in the url.)


John Avis
# Posted by Pooh · January 16, 2009

Yes i know.
but result on addressbar was show
it show ParaName and ParaValue on
address bar

Not like your example :
yor result on address bar :

result on address bar not show
ParaName(model and year)

what should i do.


# Posted by John Avis · January 16, 2009

I'm sorry but I don't understand. You can send me your code by email if you like and what url you are requesting and I will have a look.


John Avis
# Posted by jimmy · February 10, 2009

I've tried the modified script posted by John Avis, but I cannot get any results from the newpage.asp:

<% myID = Right(Request.ServerVariables("HTTP_X_ORIGINAL_URL"),2) %>
<% Response.Write(myID) %>

What exactly is the HTTP_X_ORIGINAL_URL server variable and why is it empty?

Any help would be greatly appreciated.


# Posted by jimmy · February 10, 2009

To clarify, if I try to hit:

I would expect to see myID - 24.

This does not occur and unfortunately, I have no idea how to resolve it.


# Posted by John Avis · February 10, 2009


How are you testing your scripts? They will only work if you configure a custom error page to point to that first script.

HTTP_X_ORIGINAL_URL will then give you the originally requested URL.


John Avis
# Posted by jimmy · February 27, 2009

It seems I completely missed the part about configuring custom errors. Oopsy! I'll have to have another try (if I can even setup custom error pages on my brinkster account).

However, on doing some more reading on this, does using custom error pages not affect the website logs?


# Posted by Jinesh · July 28, 2009


Thank you so much for this article...

its really helps me lot.

Jinesh Shah


# Posted by William · February 5, 2010

Hi John
Great work, Thank you for this article but i am missing the pot can youu please explain a little more. I have 3 pages the error page i called url.asp,
a category page call cate.asp and a sub cat page call shopping.asp. On the category page when click on the link i point it to go to url.asp and it won't redirect to shopping.asp.

Best Regrads


# Posted by William · February 5, 2010

also i change the page.asp to cate.asp and page.asp to shopping.asp


# Posted by John Avis · February 24, 2010

Hi William. I am very sorry for the late reply. Do you still need assistance with this? If so could yu send me the relevant parts of your code and I will see if I can help.


John Avis
# Posted by JohnBush · May 23, 2011

Hello! Very good job(this site)! Thank you man.


# Posted by barksmatt · September 12, 2011

Hi John, we followed the technique given here, initially with fine results. Except we've just been sandboxed by G for doorway pages. We're not clear but could it be a problem relating to this URL re-write? Are there any steps we may have got wrong to cause the problem? Thanks for your help!


# Posted by John Avis · September 12, 2011

I have used the technique on a few websites without problem. You are using Server.Transfer and not a redirect of some sort, right? Do you have any client side redirects? Try testing with something like ieHTTPheaders to monitor what status codes are returned when you request a page.


John Avis
# Posted by www.she7ata.com, Mohammed · October 28, 2011

Thanks for the tip, i've created a 404-tecnique years ago and it works like charm on my website, try the article on the link below ...


www.she7ata.com, Mohammed
# Posted by Ashish Rathod · February 11, 2014

I have hosted one project in my local dns

currently my url is http://classified.vesys.local/home.aspx

and i would like to change it to : http://CityName.classified.vesys.local/home.aspx

and i have to use Url Rewrite and i have to use this regular expression but this is not working

so can u please help me ...

<rule name="Rewrite subdomains">
<match url="^/?$" />
<add input="{HTTP_HOST}" pattern="http://(.+).classified.vesys.local/" />
<action type="Rewrite" url="http://classified.vesys.local/Home.aspx?subdomain={C:1}" />


Ashish Rathod
# Posted by John · February 12, 2014

My blog article is about Classic ASP URL rewriting, not ASP.NET. You are probably best posting your question on stackoverflow.com or a similar website.


# Posted by Johnf224 · December 25, 2016

Howdy! Would you mind if I share your weblog with my twitter group? Theres lots of people that I think would truly enjoy your content material. Please let me know. Thanks dkaagegekabe


# Posted by AndrewDon · February 18, 2017

Существует такая услуга - добровольное медицинское обслуживание (или ДМО).
Она предполагает, что пациент платит небольшую сумму за то, что посещает врачей целый год не платя за каждый прием.
Однако опросы показали, что лишь 6% жителей Санкт-Петербурга знают о ее существовании.
Да потому что клиникам выгоднее брать плату за каждое посещение.
А если честный врач посоветует добровольное медицинское обслуживание клиенту - это сулит ему увольнением.
Эта информация уже вызвала множество скандалов, сразу после того как информацию об этом рассекретил один возмущенный врач.
Его уволили "по собственному желанию", после того, как он предложил ДМО постоянному клиенту.
Самое страшное, что информация по ДМО присутствуют в открытом доступе, просто натыкались на эту информацию единицы.
Как отстоять свои права?
О правилах оказания услуги и обязанностях клиник можно узнать, сделав запрос в Яндексе: "добровольное медицинское обслуживание".
Именно обслуживание, а не страхование.



# Posted by Dennishag · February 21, 2017

Zhheherhrh eg egemtr hrggwe wes egemtrghdfbsgd rwtwrqw


Leave a Comment

All comments are moderated and rel="nofollow" is in use. Avatars are sourced from gravatar.com – a globally recognised avatar.

Type the numbers from the picture above

About me
John Avis ...mostly about web development and programming, with a little bit of anything else related to the Internet, computers and technology.

profile for John at Stack Overflow, Q&A for professional and enthusiast programmers

Get the latest posts delivered to your inbox.