Home » CodeDigest


How to Redirect URLs/domain Without www to With www and Vice versa - Permanent Redirection in ASP.Net
Submitted By Satheesh Babu B
On 1/23/2010 8:23:19 AM
Tags: ASP.Net,CodeDigest  

How to Redirect URLs/domain Without www to With www and Vice versa - Permanent Redirection in ASP.Net.

Search engines like Google will treat a page with url as different from http:// even though they are serving the same page on a website. Hence, there are chances that Google may penalise your website with Duplicate Content violations or your page rank will be affected. We can prevent this by redirecting users/user agents by sending a 301 status code to the url with www prefix if they are accessing without www.

For an ASP.Net application, we can use the Application_BeginRequest event in Global.asax event and Response object to do a permanent redirection with "301 Moved permanently" status code.
The below code help you to do that,

void Application_BeginRequest(object sender, EventArgs e)
        string FromHomeURL = http://;

 string ToHomeURL = http://;

                if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(FromHomeURL))

            HttpContext.Current.Response.Status = "301 Moved Permanently";

            HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace(FromHomeURL, ToHomeURL));



The above code will put a www prefix if you try to access the website without www i.e like http://

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..