CODEDIGEST InstallShield
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » CodeDigest » How to Redirect URLs/domain Without www to With www and Vice versa – Permanent Redirection in ASP.Net   You are not logged in.
Search
 

Sponsors
InstallShield
 

Sponsored Links
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
How to Redirect URLs/domain Without www to With www and Vice versa - Permanent Redirection in ASP.Net
How to Redirect URLs/domain Without www to With www and Vice versa - Permanent Redirection in ASP.Net
Submitted By Satheesh Babu
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 http://www.yourdomain.com/Default.aspx as different from http:// yourdomain.com/Default.aspx 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:// yourdomain.com;

 string ToHomeURL = http:// www.yourdomain.com;

                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:// yourdomain.com.
      

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..