Friday, 27 June 2014

How to resolve canonical url issue in asp.net

In this article we will see how we can resolve canonical url issue. As we know www and non-www urls are treated as 2 different types of urls. so how we can solve this issue.
Example
- yourdomain.com
- www.yourdomain.com

Method 1:
One way is to rewrite the url based on the match. Let's say a user comes to visit with non-www url (it will be your match pattern) on your site then you can rewrite that url to a www url.
We can add following rule to web.config to handle this situation.
 <system.webServer> <rewrite> <rules>
 <rule name="Redirect to www" >
 <match url="(.*)" ignoreCase="true" />
 <conditions>
 <add input="{HTTP_HOST}" pattern="^yourdomain\.com" />
 </conditions>
 <action type="Redirect" url="http://www.yourdomain.com/{R:1}" redirectType="Permanent" />
 </rule>
 </rules>
 </rewrite>
 </system.webServer>

NOTE: In this case you will have to install the  url rewriter tool. And it will work for IIS 7.0 and above.
============================================================================================
Method 2:
you can also do a 301 redirect using global.ascx. you can check if the url is non-www url, if so you can replace it with www url and do a redirect.

 void Application_BeginRequest(object sender, EventArgs e)
 {
            string nonWWWUrl = @"http://yourdomain.com";    
            string WWWUrl = @"http://www.yourdomain.com";
  
            if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(nonWWWUrl))
            {
                HttpContext.Current.Response.Status = "301 Moved Permanently";
                HttpContext.Current.Response.AddHeader("Location",
                Request.Url.ToString().ToLower().Replace(nonWWWUrl, WWWUrl));
            }
 }
ref : http://www.gilgh.com/article/how-to-resolve-canonical-url-issue-in-asp-net

No comments:

Post a Comment