Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Contributing User
    ASP Explorer (0 - 99 posts)

    Join Date
    Mar 2006
    Posts
    31
    Rep Power
    14

    How-To: URL Rewriting with ASP/IIS


    Since I see the question around so often and have asked it myself for years, I thought I would post my solution to getting effective URL rewriting working in ASP.

    For example, your current URLs look something like
    Code:
    http://www.mytestdomains.com/products.asp?id=342
    , but you want them to look like
    Code:
    http://www.mytestdomains.com/products/342/
    . For various reasons, the latter form is preferred by most people.

    We'll assume for the time being that your existing site already works with the querystrings (although if you write a new web-app from scratch, you can ignore them completely).

    First, create a new ASP file - we'll call ours "rewrite.asp". In that file, all it needs to do is grab the querystring that IIS will give it, strip our server name from it, and then store the remaining URL in an array. Once we have the array (or better, a Class with a property that reflects the array), we call
    Code:
    server.transfer
    to transfer control to our existing files. This way, the browser (or robot, or whatever) will only see the URL they typed in, but the server will execute the page we want it to.

    Example code for "rewrite.asp":
    asp Code:
    Class URL
     Private aURL ' the array that contains our URL elements
     Private Sub Class_Initialize()
      sTemp = Request.Querystring
      ' the next line removes the HTTP status code that IIS sends, in the form "404;" or "403;" or whatever, depending on the captured error
      sTemp = Right(sTemp, len(sTemp) - 4)
      ' the next two lines remove both types of server names that IIS includes in the querystring
      sTemp = replace(sTemp, "http://www.mytestdomains.com:80/", "")
      sTemp = replace(sTemp, "http://www.mytestdomains.com/", "")
      ' the next bit of code will force our array to have at least 1 element
      If Right(sTemp, 1) <> "/" then
       sTemp = sTemp & "/"
      End If
      aURL = split(sTemp, "/")
     End Sub
     Public Property Get url(index)
      If index > uBound(aUrl) then
       url = ""
      Else
       url = trim(aUrl(index))
      End If
     End Property
    End Class
     
    Set MyUrl = New URL
     
    Server.Transfer("/" & MyUrl.url(0) & ".asp?id=" & MyUrl.url(1))


    Now, what this file does is receive a querystring from IIS that contains an error number (which we ignore here) and the URL that was asked for. We strip our server name from the URL and break the remainder into an array that we can reference from anywhere. This is a simple example, just taking the first element of the URL as the page name, and the second element as an ID of some sort. So we can request
    Code:
    http://www.mytestdomains.com/products/342
    , and the server will show us
    Code:
    http://www.mytestdomains.com/products.asp?id=342
    .

    The final step requires that you create some custom errors in IIS.

    Using the IIS manager (or your tool of choice), the following errors must be changed to have a message type of URL with "/rewrite.asp" as the URL.
    • 403;14 (Forbidden - Directory Listing Denied)
    • 404 (Not Found)
    • 405 (Method Not Allowed)
    • 500;15 (Internal Server Error - Direct requests for GLOBAL.ASA)

    The 403, 404, and 500 errors should make sense - if someone requests a folder without a default document (that should be turned off, by the way, if you're rewriting URLs), requests a non-existent file or path, or tries to access the "global.asa" file, the "rewrite.asp" file should do it's magic. The 405 error is a little different - capturing that one and rewriting it lets POSTed form information be redirected as well.

    I've implemented this solution (though slightly less simplified) a few times now with great success. I can't promise to be able to answer every single question (if anyone has any, that is), but I'll try.

    Comments on this post

    • Shadow Wizard agrees : good stuff, thanks for sharing! :)
    • KiReSt agrees : Thanks, will probably be using this on my new site.
    Last edited by Rust Indy; March 11th, 2006 at 07:18 PM. Reason: Title change
  2. #2
  3. Moderator From Beyond
    ASP Mastermind (5000+ posts)

    Join Date
    Sep 2004
    Location
    Israel
    Posts
    31,135
    Rep Power
    2926
    welcome to aspfree and thanks for sharing, your post has been moved
    to the Code Bank.
  4. #3
  5. No Profile Picture
    Contributing User
    ASP Explorer (0 - 99 posts)

    Join Date
    Mar 2006
    Posts
    31
    Rep Power
    14
    Thanks!

    It should also be noted that since ASP 3 (IIS5 and up) supports regular expressions, this class could be rewritten to handle MOD_REWRITE-like rules. Someone with more motivation (and understanding of regexps) will have to do it though.
  6. #4
  7. No Profile Picture
    Registered User
    ASP Explorer (0 - 99 posts)

    Join Date
    May 2006
    Posts
    2
    Rep Power
    0
    Hello,
    I really like your code and it looks like it will help me achieve exactly what I'm trying to do.

    Unfortunately, it breaks right at the end.

    Originally Posted by Rust Indy
    Server.Transfer("/" & MyUrl.url(0) & ".asp?id=" & MyUrl.url(1))
    Server.Transfer cannot handle querystrings ("?")!

    How did you get it to work?

    Many thanks,
    Blackwater
  8. #5
  9. No Profile Picture
    Contributing User
    ASP Mastermind (5000+ posts)

    Join Date
    Aug 2005
    Location
    North East, UK
    Posts
    6,191
    Rep Power
    141
    That's a good question.

    Personally, I do not like this implementation because basically you are redirecting all of your site traffic through your error pages.
    They are there for a reason. It also messes up your logs.
  10. #6
  11. No Profile Picture
    Registered User
    ASP Explorer (0 - 99 posts)

    Join Date
    May 2006
    Posts
    2
    Rep Power
    0
    Originally Posted by degsy
    That's a good question.

    Personally, I do not like this implementation because basically you are redirecting all of your site traffic through your error pages.
    They are there for a reason. It also messes up your logs.
    Thanks for the reply.

    I managed to get around it by putting the querystrings in session variables - not the ideal solution, but it's working.

    A agree about it messing up your logs.. what other options are there?

    Cheers,
    Blackwater
  12. #7
  13. No Profile Picture
    Contributing User
    ASP Mastermind (5000+ posts)

    Join Date
    Aug 2005
    Location
    North East, UK
    Posts
    6,191
    Rep Power
    141
    There are utilities available that you can install that will act like Apache Mod_Rewrite.

    http://www.google.co.uk/search?hl=en&q=IIS+url+rewrite&meta=
  14. #8
  15. No Profile Picture
    Registered User
    ASP Explorer (0 - 99 posts)

    Join Date
    Jun 2006
    Posts
    1
    Rep Power
    0

    confused!!!!!!!


    I have gone through your code. But I have some problem regarding URL rewriting in ASP. I have created a file “rewrite.asp” and place your code there. Now the problem is that I cannot able to place this code into its exact place in my application to get desired output. Please help me how and where to implement this code in my application soon. One more things is that I have no “global.asa” .


    looking forward to your reply soon
  16. #9
  17. Kingpin contributor
    ASP Good Citizen (1000 - 1499 posts)

    Join Date
    Nov 2005
    Location
    P.E, RSA
    Posts
    1,051
    Rep Power
    211
    Very usefull Rust Indy.

    Consider looking at how easy this is to achieve with URL Mapping in ASP.NET 2.0

    ASP.NET 2.0: URL Mapping with RegEx Support

    Jo.
    Last edited by D.O.M.I.N.A.T.O.R; June 13th, 2006 at 04:10 AM.
  18. #10
  19. No Profile Picture
    Contributing User
    ASP Discoverer (100 - 499 posts)

    Join Date
    Dec 2005
    Posts
    169
    Rep Power
    15
    You can even use isapirewrite component which is free (lite version). Currently my site http://www.bepenfriends.com is using that for rewriting the URL. THis won't fill the log file with error codes and it is comeratively fast. easy to configure. single line of regEx will change everything.

    http://www.helicontech.com/ is the website

    /products/(\d+) /product.asp\?ID=$1 [I,L] will do the same with the same directory format which you specified in the article.

    But the only problem is this will not work if you have a shared host because in a shared hosting you are not having root access to install the control.

    Albert
    http://www.bepenfriends.com
  20. #11
  21. Expert Learner
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Feb 2005
    Location
    Wisconsin
    Posts
    1,909
    Rep Power
    102
    I have used ISAPI Rewrite as well. The benefit out of the 404 rewrite that I have noticed is that the rewrites can be dynamic...you can use loops and such in the 404.asp file. It's pretty neat.
  22. #12
  23. Expert Learner
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Feb 2005
    Location
    Wisconsin
    Posts
    1,909
    Rep Power
    102
    But you can set it up that if the URL still does not match a current page, it can still show a typical 404 page.

    By the way, everyone make sure that in the rewrite page, if it determines it to be showing the correct page, you are adding the line

    Response.Status = "200 OK"

    to make it so that it's not a 404 anymore.

    Dealing with the Server.Transfer issue, I don't use it. I include the file in the 404 page.

    Code:
    <%
    If MyUrl.url(0) = "directory" Then
         Response.Status = "200 OK"
         variable = MyUrl.url(1)
         %><!-- #Include Virtual = "variable.asp" --><%
    End If
    %>
  24. #13
  25. No Profile Picture
    Registered User
    ASP Explorer (0 - 99 posts)

    Join Date
    Oct 2003
    Posts
    3
    Rep Power
    0
    just need this code,thanks!

    __________________
    Solid Offshore Bulletproof Hosting and BP Server[/URL]
  26. #14
  27. No Profile Picture
    Contributing User
    ASP Explorer (0 - 99 posts)

    Join Date
    Nov 2005
    Posts
    84
    Rep Power
    14
    Hi all

    Could somebody help me , I need this script
    I found this :

    Code:
    Function Redirect_Rewrite( ByVal sSourcePage )
    'Trigger function for inline rewrites if required
    
    'demo code assumes that pages are named /products/123456.htm or 
    ' /products/item123456.htm and parses them accordingly, this
    ' this would allow you to hook into a database and generate the 
    ' appropriate page for that item number.
    
    Const csDirName = "/products/"
    Const csPrefix = "item"
    
    ReDirect_ReWrite = False
    
    'Normalise the input
    sSourcePage = Trim(LCase( sSourcePage ))
    
    If Left( sSourcePage, Len( csDirName ) ) = csDirName Then
        'Trim the directory
        sSourcePage = Right( sSourcePage, Len( sSourcePage ) - Len( csDirName ) )
    	
        'Trim the suffix
        If Right( sSourcePage, 4 ) = ".htm" Then
            sSourcePage = Left( sSourcePage, Len( sSourcePage ) - 4 )
        ElseIf Right( sSourcePage, 5 ) = ".html" Then
            sSourcePage = Left( sSourcePage, Len( sSourcePage ) - 5 )
        End If
    
        'Trim any prefix
        If Left( sSourcePage, 4 ) = csPrefix Then
            sSourcePage = Right( sSourcePage, Len( sSourcePage ) - Len( csPrefix ) )
        End If
    	
    	'Create page for output
        Response.Status = "200 OK"
        Response.Write "-- your header code --"
        Response.Write "Your product code was '" & sSourcePage & "'."
        Response.Write "-- your footer code --"
        ReDirect_ReWrite = True
    End If
    
    End Function
    From here http://evolvedcode.net/content/code_smart404/guide-rewrites.asp

    and this :

    Code:
    Dim strRefer 
    strRefer = lcase(Request.ServerVariables("QUERY_STRING")) 
    
    if instr(1, strRefer, "/exmaple1/") then 
    
    Response.Status = "200 OK" 
    Server.Transfer("/example2/file.asp") 
    
    elseif instr(1, strRefer, "/example3/") then 
    
    Response.Status = "200 OK" 
    Server.Transfer("/example3/file.asp") 
    
    elseif instr(1, strRefer, "/example3/") then 
    
    Response.Status = "200 OK" 
    Server.Transfer("/example4/file.asp") 
    
    else 
    
    Server.Transfer("/error.asp") 
    
    end if
    from here http://www.webmasterworld.com/forum47/3267.htm

    could somebody merge these codes with which in this topic and make a good code for rewriteing ?
    I need that
    Shadow wizard please could you do this
  28. #15
  29. Moderator From Beyond
    ASP Mastermind (5000+ posts)

    Join Date
    Sep 2004
    Location
    Israel
    Posts
    31,135
    Rep Power
    2926
    why me? I didn't write this thread and none of the codes you have is mine.

    anyway, if you want URL Rewriting check this before trying to re-create the wheel:
    http://www.isapirewrite.com/
    they have freeware version available as well.
Page 1 of 2 12 Last
  • Jump to page:

Similar Threads

  1. URL rewriting - authentication problem
    By newtoaspdotnet in forum .NET Development
    Replies: 0
    Last Post: July 28th, 2005, 03:39 PM
  2. URL rewriting & subdomains
    By newtoaspdotnet in forum .NET Development
    Replies: 2
    Last Post: March 25th, 2005, 02:53 PM
  3. If Not IsNull statement, Help rewriting it. Please
    By Asperation in forum ASP Development
    Replies: 5
    Last Post: August 16th, 2004, 09:36 PM
  4. URL rewriting tool for IIS
    By Steve Schofield in forum .NET Development
    Replies: 0
    Last Post: March 10th, 2002, 06:21 PM
  5. URL rewriting tool for IIS
    By Steve Schofield in forum ASP Development
    Replies: 0
    Last Post: March 10th, 2002, 06:20 PM

IMN logo majestic logo threadwatch logo seochat tools logo