A smartphone and a pen on a desk

How to add cannonical URL to a Hugo blog?

In SEO, it is good practice to include a canonical link in the head element of each page. Using Hugo static site generator, how do you do it? Let's dive right in.

I’m using the Hugo theme stack from Jimmy Cai.

It already includes in the head template the code to add a canonical link.

But, at one stage, I had to set a link from an article I published on a publishing platform.

Therefore, I couldn’t let the theme generate a canonical link automatically.

The goal

I wanted to keep the automation for articles first published on my blog.

Then, in some cases, I wanted to republish an article on my blog while it was already available on the Internet.

Why

In SEO, the best practices are:

  • Each webpage must have a canonical link.
  • A single webpage with the same content must be published once and only once in the Internet.

If you break those two rules, then the web crawlers won’t index your pages and you will miss out on some traffic.

Solution using the Hugo theme stack

First I had to find where the canonical link was generated. I found it in layouts/partials/head/head.html:

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

Now, how could I specify within the frontmatter of a given article that I wanted the canonical link to be a specific one?

With a little search, I’ve found this thread on the Hugo forum.

The frontmatter data is accessible through .Params that contains key/value pairs.

The key is the name of the frontmatter property.

In my case, I named the canonical relcanonical and the value had to be a string.

It gives you the following:

1
2
3
---
relcanonical: https://iamjeremie.me
---

The head.html line above had to change to the following:

1
2
3
4
5
{{ with .Params.relcanonical }}
<link rel="canonical" href="{{ . | relLangURL }}" itemprop="url" />
{{ else -}}
<link rel="canonical" href="{{ .Permalink }}" itemprop="url" />
{{ end -}}

In the above code,

  • When the relcanonical is set ({{ with .Params.relcanonical }})
  • Use its value, which is the . in {{ . }}.

The moustache syntax is used for Go programming within the HTML template

I hope you found this useful.

Credit : Photo by Steve Johnson on Unsplash.

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy