
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.
TaDa! Solutions is operated by genuine wizards. Never once have we made a request for something they couldn’t create. They are transparent with costs and timing, always make their promised timelines, produce quality work, and are easy to deal with in the process. They really are the ideal partner for website and database development.
Matthew Ulmer
VP of Operations & Client Relations
Arc Intermedia
Over the past 7 years, our nonprofit organization has greatly benefited from the exceptional development work provided by TaDa! Solutions. Their team has demonstrated a deep understanding of our mission and unique needs, translating that to user-friendly websites and an ordering and client management system that has earned rave reviews. Their expertise and dedication have been invaluable in expanding our reach and impact. We wholeheartedly recommend them to any organization seeking a reliable, creative, and truly supportive technology development partner.
Mike Gerber
Senior Director of Information Technology
Open Hand Atlanta