Add a Canonical URL tag to your Hugo site


While working with a barebone Hugo theme, I noticed that it doesn’t have a canonical URL meta tag. I have a publicly accessible development site because of the inticracies of my deployment procedure, and it is quite important that it is not picked up and indexed by search engines. Canonical URLs become really important in this context.

Well, thankfully it was really easy to add. I needed to override the template file that defined the <head> section of our pages. For me, it was /layouts/partials/header.html, but it can be something different based on how your theme/template is set up - another common place is /layouts/_default/baseof.html. You might need to override your theme’s default template file by copying it from your theme folder (/themes/theme-name) and putting it in your layout folder.

Once you have located/created the file, just add this to the <head> section.

<link rel="canonical" href="{{ .Permalink }}" />