Canonical Urls in Sitecore

Posted 01/15/2014 by Emer Kurbegovic

In some cases users can get to a particular Sitecore page via multiple urls. This is generally not good practice since Google and other search engines treat that page as duplicate content which then affects its ranking.

This is easily fixed by using canonical tag on your page. Adding this link tag and attribute lets site owners identify sets of identical content and suggest to Google: "Of all these pages with identical content, this page is the most useful. Please prioritize it in search results."

The Canonical URL tag attribute is similar in many ways to a 301 redirect from an SEO perspective. In essence, you're telling the engines that multiple pages should be considered as one (which a 301 does), without actually redirecting visitors to the new URL (often saving your dev staff considerable heartache).

Canonical link tag looks something like this:

<link rel="canonical" href="http://therealpage.com" />

To render canonical tag on your site add below code to your master page:

public static string GenerateCanonicalTag()
{
    var request = HttpContext.Current.Request;
 
    var uri = new Uri(request.Url, request.RawUrl);
    string url = uri.AbsolutePath;
    string baseUrl = uri.GetComponents(UriComponents.Scheme | UriComponents.Host, UriFormat.Unescaped);
 
    if (Sitecore.Configuration.Settings.AliasesActive && Sitecore.Context.Database.Aliases.Exists(url))
    {
        Sitecore.Data.Items.Item targetItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Database.Aliases.GetTargetID(url));
        return string.Format("{0}{1}", baseUrl, Sitecore.Links.LinkManager.GetItemUrl(targetItem));
    }
 
    string itemUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item);
    if (url != itemUrl)
    {
        return string.Format("<link rel=\"canonical\" href=\"{0}{1}\" />", baseUrl, itemUrl);
    }
    return null;
}


Then add following to your .aspx page within the <head> tag:

<%= GenerateCanonicalTag() %>

 

Share:

Archive

Syndication