Tuesday, March 31, 2015

Redirecting non-www requests to www requests

Redirection of Non-WWW domain to WWW (301 Redirection – permanent) is very important for ranking on search engine like Google.

The Problem is that the Google search consider http://domain.com to be a different domain than http://www.domain.com. so it makes the difference in search engine back links because you have made it with and without www prefix.

It is better to have every link use exactly the same form of your domain. for this purpose, it is common to redirect request from non-www to www.

We can do it in asp.net by many ways but I mentioned 2 solutions below -

1. web.config : 

       It is most common practice to do the redirection from non-www to www because we don’t have the IIS access on shared hosting environment.

Make sure you replace example.com with the name of your domain.

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Redirect to WWW" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^example.com$" />
          </conditions>
          <action type="Redirect" url="http://www.example.com/{R:0}"
                  redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>


2. Global.asax.cs  : 

          If you wish to do it from within your application, use the Application_BeginRequest in Global.asax.cs to intercept the request and do a 301 (permanent) redirection on the url.

 NOTE - you will need to set up the bindings of the site in IIS to accept both the www.domain.com and domain.com host names.

protected void Application_BeginRequest(object sender, EventArgs ev)
{
   string FromHomeURL = "http://www.example.com";
   string ToHomeURL = "http://example.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));
   }
}

Happy Coding !! 

No comments:

Post a Comment