Adding an External Canonical URL to a Hugo Template

Chris Concannon
Feb 23 · 2 min read

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:

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!

Chris Concannon

Written by

former biomedical engineer, current web application developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade