Adding an External Canonical URL to a Hugo Template

Chris Concannon
2 min readFeb 23, 2019


Not paying for Medium? Find most of the same content of this post here:

Last year, I decided to create a personal website/blog while I was learning to deploy static-content websites via AWS. I chose to use the Hugo framework and the Minimal Academic theme.

I recently decided that I want to cross-post content that I wrote for other sites to my personal website. This content includes a mix of Medium posts (including this one) and company blog posts. In accordance with best practices for cross-posting identical content across multiple sites, I decided that using a canonical url tag in the individual .html page headers was a good idea.

I couldn’t find a straightforward answer on how to do this with Hugo, but I realized that my chosen Hugo template was already creating a <link rel="canonical" href="{my-hugo-site-page-path}"> in the header of each html content page. I needed to find out how to conditionally override this to reflect something like <link rel="canonical" href="{original-content-path-at-another-domain}">.

Fortunately for me, the fix was relatively simple after I consulted the Hugo front matter documentation. I defined a custom front matter variable called canonicalUrl in the relevant markdown content files. I assigned the value of this variable to the original content url. Then, per the Hugo documentation on layout lookup order (and in accordance with my chosen theme folder structure) I created a new file at /layouts/partials/header.html. I copied over the content of /themes/{my-chosen-theme/layouts/partials/header.html to the file I just created.

In my newly-created /layouts/partials/header.html file, I found the definition of the <link rel="canonical" href="{{ .Permalink }}"> and replaced it with a statement that looks for the existence of my custom front matter variable, and (when applicable) assigns that value to the href property in my html header:

{{ if .Params.canonicalUrl }}
<link rel="canonical" href="{{ .Params.canonicalUrl }}">
{{ else }}
<link rel="canonical" href="{{ .Permalink }}">
{{ end }}

Now when I define a canonicalUrl: “{original-content-path}" param in the front matter of a new site page, the header of the resulting .html page is built with the canonical link embedded.

Thanks for reading!