
We recently implemented custom canonical tags for our customers. Many of our customers have several domain names that point to a single site. They wanted to be able to set a canonical domain name for the site and sometimes override the canonical url per page.
Our Solution
This is a pretty easy problem to solve. Here's what we decided on.
Umbraco Document Type Changes
Code Changes
We created a simple extension method to allow for the Canonical Url to be an extension of IPublishedContent available for Umbraco models. You can just add this to a class file in your App_Code folder for a simple site or as part of a dll for a more complex project.
public static string GetCanonicalUrl(this IPublishedContent node) { IPublishedContent root = node.Root(); string canonicalDomainName = root.Value<string>("canonicalDomainName"); string canonicalUrl = ""; if (node.HasValue("canonicalLinkOverride")) { string canonicalLinkOverride = node.Value<string>("canonicalLinkOverride"); if (canonicalLinkOverride.StartsWith("http")) // absolute url { canonicalUrl = canonicalLinkOverride; } else // not an absolute url { if (canonicalLinkOverride[0] != '/') // correct user entries that don't include a leading slash { canonicalLinkOverride = "/" + canonicalLinkOverride; } canonicalUrl = canonicalDomainName + canonicalLinkOverride; } } else if (canonicalDomainName != "") { canonicalUrl = canonicalDomainName + node.Url(); } return canonicalUrl; }
View Updates
In your master template, simply add this code. (Note: We actually add this in a header partial view surrounded by an if not empty string statement.)
<link rel="canonical" href="@Model.GetCanonicalUrl()" />
That's it. With these simple additions, we added canonical links.