Here are instructions on how to get Canonical URLs working by using a Razor Macro on Umbraco version 7.1.x
Step 1 – Create the Macro
- Log into the Umbraco admin panel
- Go to the Developer tab
- Right click on Scripting Files, choose ‘Create’
- Assign a file name (I used “CanonicalUrl” for my file name)
- Chose a language. I used .cshtml (Razor Macro Engine)
- Choose “Empty template” for the snippet
- Leave ‘Create Macro’ checked
- In the scripting file, paste in one of the code sections below depending on whether you want “www.” to appear in your
canonical URL. - Save the file (you shouldn’t see any errors)
Step 2 – Update your layout
- Go to the ‘Settings’ tab
- Under ‘Templates’, find your master layout template. Mine is called “Layout” but yours might be something else.
- In the `<head>` section of the template, insert the Macro you just created. For me, this was `@Umbraco.RenderMacro
(“CanonicalUrl”)`. Yours might be different if you chose a different name. Use the insert macro button if you can’t recall the
exact name. - Save the template
- Test by inspecting the `<head>` section of your site to be sure the canonical URL is correct after attempting to reach
your site using a variety of methods: yoursite.com, www.yoursite.com, http://yoursite.com, http://www.yoursite.com. Make sure
to check your interior pages as well.
If you DO WANT the www to appear in your canonical URLs, use this code:
@using umbraco @using System @{var canonicalUrl= String.Empty;} @if(umbraco.library.RequestServerVariables ("HTTP_HOST").ToLower().StartsWith("www")) { canonicalUrl = string.Concat("http://", umbraco.library.RequestServerVariables("HTTP_HOST"), Model.Url); } else { canonicalUrl = string.Concat("http://www.", umbraco.library.RequestServerVariables("HTTP_HOST"), Model.Url); } <link rel="canonical" href="@canonicalUrl" />
If you DO NOT want the www to appear in your canonical URLs, use this code instead:
@using umbraco @using System @* empty out the string *@ @{var canonicalUrl= String.Empty;} @* check if the requested URL starts with www. *@ @if(umbraco.library.RequestServerVariables("HTTP_HOST").ToLower().StartsWith("www")) { @* adds http:// to the beginning *@ canonicalUrl = string.Concat("http://", umbraco.library.RequestServerVariables ("HTTP_HOST"), Model.Url); @* strips out the www. from the URL *@ canonicalUrl = umbraco.library.Replace(canonicalUrl, "www.", ""); } else { @* if they did not use the www prefix, we still have to add http:// to the URL *@ canonicalUrl = string.Concat("http://", umbraco.library.RequestServerVariables("HTTP_HOST"), Model.Url); } <!-- output the canonical URL --> <link rel="canonical" href="@canonicalUrl" />
Still having trouble? Call in the reinforcements.