SEO Tip: Set Preferred URL in ASP.NET Application

Search engines treat website URL with and without “www” differently. Though both URLs point to the same destination, it’s important to pick one and set as your preferred URL so that search engines don’t two URLs as duplicate content. Websites use 301 redirect for this.

The example code to redirect non-www URL to www URL in an ASP.NET application would be as following. Add following code snippet in Application_BeginRequest method of your Global.asax. Replace URL (somewebsite.com) with your website URL in the code and you are all set.

protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith("http://somewebsite.com"))
    {
        string newUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Replace("http://somewebsite.com", "http://www.somewebsite.com");
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", newUrl);
    }
}

If you want to do the opposite and direct www URL to non-www URL simply change the code as following

protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith("http://www.somewebsite.com"))
    {
        string newUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Replace("http://www.somewebsite.com", "http://somewebsite.com");
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", newUrl);
    }
}

It does not make a different to search engines which one (www or non-ww) do you prefer but you do need to pick one of the two URLs as your preferred URL to improve SEO ranking of your site.


Leave A Comment

Your email address will not be published.