Search code examples
hugocanonical-link

How to write a canonical URL in Hugo?


I am trying to create a canonical URL for my web site by some tutorials in the web but I was not able to create a canonical URL. It always shows the current URL.

I have layouts\partials\docs\inject\head.html.

{{- if isset .Params "canonical" -}}
  <link rel="canonical" href="{{ .Params.baseURL }}" />
{{- else -}}
  <link rel="canonical" href="{{ .Permalink }}" />
{{- end }}

And also I have config.toml.

baseURL = 'https://example.com/'
languageCode = 'en-us'
title = 'Hello world!'
theme = 'hugo-book'

[params]
  canonicalUrl = 'https://example.com/'

Bu it always shows the current link and not the canonical url. Like

  <link rel="canonical" href="http://localhost:1313/docs/hello/" />

while I expect to see:

  <link rel="canonical" href="https://example.com/docs/hello/" />

What is the proper way to show a canonical URL in Hugo?


Solution

  • In this case I believe you are running into the difference between running in the CLI "hugo" vs "hugo server".

    Build your file with "hugo" and then check the canonical link in the files output.