Canonical URLs in Umbraco CMS version 7.1.x with Razor

By November 26, 2014SEO

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

  1. Log into the Umbraco admin panel
  2. Go to the Developer tab
  3. Right click on Scripting Files, choose ‘Create’
  4. Assign a file name (I used “CanonicalUrl” for my file name)
  5. Chose a language. I used .cshtml (Razor Macro Engine)
  6. Choose “Empty template” for the snippet
  7. Leave ‘Create Macro’ checked
  8. In the scripting file, paste in one of the code sections below depending on whether you want “www.” to appear in your
    canonical URL.
  9. Save the file (you shouldn’t see any errors)

Step 2 – Update your layout

  1. Go to the ‘Settings’ tab
  2. Under ‘Templates’, find your master layout template. Mine is called “Layout” but yours might be something else.
  3. 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.
  4. Save the template
  5. 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:,,,  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.

Talk now: 323-813-1789

mautic is open source marketing automation