September 06, 2010

Implementing 301 Redirects for ASP Sites at the Application Level.

 

The easiest way is doing it in IIS Level. But if you have shared hosting, where you do not have control on the Web Server and your hosting provider didn’t agree to do it, you have no option other than doing it at the application level.

So you need to include the following code in all of your ASP pages

<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location", "www.freemanortho/new-page.asp"
%>

Whereas this will not work in FireFox and the following error message is thrown.

“The page isn't redirecting properly .firefox has detected that the server is redirecting the request for this address in a way that will never complete. '”

What if you have 1000+ pages and it is difficult to change and hardcode in all the pages , that is time consuming and maintenance headache. What if a new page is created, then again you need to write this code too.

We need to write a best practice more generic approach that gives optimized output, better results with a minimum overhead

Instead of hard coding domain names and page names

Get Domain Name

Get Domain name using request.ServerVariables("HTTP_HOST"))

Get Path Name

The path of the pages can be dynamically get by = request.ServerVariables("PATH_INFO")

Get QueryString

If there is querystring append the querystring to the URL along with path name.

request.ServerVariables("QUERY_STRING")

We can even now  handle the querystrings if any in the live websites by appending pathname and querystring to the url.

Use the below code to redirect the pages dynamically.

<%

Domain_Name = lcase(request.ServerVariables("HTTP_HOST"))

if domain_name <> "www.freemanortho.com" Then

HTTP_PATH = request.ServerVariables("PATH_INFO")

QUERY_STRING = request.ServerVariables("QUERY_STRING")

theURL = "http://www.freemanortho.com" & HTTP_PATH

if len(QUERY_STRING) > 0 Then

theURL = theURL & "?" & QUERY_STRING

end if

Response.Clear

Response.Status = "301 Moved Permanently"

Response.AddHeader "Location", theURL

Response.Flush

Response.End

end if

%>

Create a file called Redirect.asp and

Now include this file in the include file in the header.asp .
<!-- #Include file="redirect.asp" -->

As the header.asp is the include file that is called in all the pages, the code gets called in all the pages.

Now our site, gets redirected to www.freemanortho.com instead of http://freemanortho.com throughout the site in any page

1 comment:

Venkateshwara Rao said...

I hate VB........ but by reading ur blogs me getting a bit intrest