301 (Moved Permanently) Permanent Redirects in Global.Asax

Dated: 25 Nov, 2010 06:05:01 PM

Recently I found that my website is not accessible through http://manishdalal.com. This is because of the application logic to prevent the site from sending duplicate contents to the search engines and make them (search engines) punish my site. I recently found that when the site is accessed through http://manishdalal.com, it displays page not exist for all the links. So I sit today to perform a 301 Permanent Redirect to tell the search engines that both these sites are one and also to redirect the users to http://www.manishdalal.com.


I decided to do that in global.asax instead of master page or every asp.net page. The steps required to do that is provided below:

  1. Get the current requested URL
  2. Check if the URL does not starts with http://www.
    1. If so, perform a permanent redirect

The code to implement this is provided below

//get the current context object
HttpContext ctx = HttpContext.Current;

//1. get the url requested
string url = ctx.Request.Url.ToString().ToLower();

//1a. if the url does not start with http://www. do a 301 redirect
if (!url.StartsWith("http://www."))
{
  ctx.Response.Status = "301 Moved Permanently";
  ctx.Response.AddHeader("Location",
                     url.Replace("http://", "http://www."));
}

Yes, this is the code live on my website. You can try to access this site with http://manishdalal.com and will find that you are redirected to http://www.manishdalal.com/default.aspx

I tested the response header of my website using http://web-sniffer.net/ and found that for http://manishdalal.com, the HTTP Response Header status reads “HTTP/1.1 301 Moved Permanently” while for http://www.manishdalal.com, the response header status reads “HTTP/1.1 200 OK

Finally, for all my site pages any request without www is automatically redirected to the same link with www, and the search engines will also put www.manishdalal.com and manishdalal.com as the same website.


Like this article? Now share it with your friends

 

0 Comments.....
Be the first one to comment.



Post Comment

Name:  
Email:  
You will receive an email to approve your comment.

Comment:  


Free subscriptions
Provide your email address to recieve my articles by email. I will never share your address, and there is a link to unsubscribe in every mail.



Follow me on twitter @mndworld

Popular Articles

Recent Articles