Wednesday, December 28, 2005

IIS 301 redirects using the 404 error page

We have always used IIS for the infrastructure of our main site. There is no way I'm going to be changing it either, as it's a huge site.
IIS can be a nightmare when it comes to redirects and URL rewrites, as there is no easy way to do it. Apache has the .htaccess file, which is incredibly powerful.
There is a way with IIS. When a non-existant page is requested from an IIS server, it can be configured to silently redirect to a custom error page, and this error page can be an ASP file. When I say "silently" I mean no codes are returned (no 200, 404, nothing). If you do this, make sure you set the 404 error code in the asp error page. This is done with the following line:
Response.Status="404 Not Found"
Make sure you do this. I didn't, and when Google crawled, it thought my 404 pages were actually loading ok (thousands of them, and all with the same content - Not good)

Now, onto the redirect/rewrite thing. The URL that returned the 404 error is actually passed to your custom 404 page in a querystring (not displayed in the browser). You can use the Request.ServerVariables(QUERY_STRING) to return this url.

From there, it's as easy as using a simple if statement to determine if the page that you want to redirect from has been called. If it has, you can set a 301 or 302 status and redirect accordingly. This is the beauty of the server not setting the 404 code for you. You can basically do what you want from this file. Server.Transfer can also be used for URL rewriting, as this can send the user to another page without changing the url in the browser, and can return a 200 code for the page they originally requested.

It's definately worth testing this before implementation, as you can get some nasty endless loops when things get complicated.

It saved me by allowing me to redirect a certain .htm page with a 301 perminant code. Here is the code that sits in my custom 404 file:

dim eurl
eurl=Request.ServerVariables("QUERY_STRING")
if eurl="404;http://www.mysite.au:80/default.htm" or eurl="404;http://mysite.com.au:80/default.htm" then
Response.Status="301 Moved Permanently"
Response.AddHeader "Location", ("http://www.mysite.com.au/")
Response.end
end if

No comments: