Dominik Honnef

Generating Netlify _redirects from Hugo

Published:
Last modified:
by

Hugo lets us add aliases to pages. This is useful to, for example, transition from an old URL scheme without breaking existing links.

Hugo achieves this by generating additional HTML files, which contain <meta> tags to specify the canonical URLs and to redirect to them.

However, if you host your Hugo site on Netlify, you might want to use its _redirects file instead. This uses HTTP-based redirects using the Location header. This should be ever so slightly faster, as the browser won’t have to parse an HTML document to discover the redirection. Furthermore, HTTP clients like curl will not know how to handle <meta> tags but will be able to follow header-based redirects.

We can generate a _redirects file from Hugo by defining a new media type and a layout for it.

First, add the following to your config.toml:

disableAliases = true

[outputFormats.REDIR]
mediaType = "text/netlify"
baseName = "_redirects"
isPlainText = true
notAlternative = true

[mediaTypes."text/netlify"]
delimiter = ""

[outputs]
home = ["HTML", "RSS", "REDIR"]

This specifies a new output format called REDIR, with all the attributes required to generate a plain text _redirects file. We then use this format in the list of outputs for our home page. This defaults to ["HTML", "RSS"] and we’ve added "REDIR" to it.

We also set disableAliases = true to prevent Hugo from generating the <meta>-based redirection pages. We won’t need them anymore.

The next and last step necessary is to write a layout for the _redirects file. This goes in layouts/index.redir and looks like this:

{{ range $p := .Site.AllPages }}
{{- range .Aliases -}}
{{ . }} {{ $p.RelPermalink }}
{{ end }}
{{- end -}}

That’s it! The next time you run hugo, it will generate a Netlify-compatible _redirects file at the top-level of the output directory.

This article is based on a commit in the git repository of Hugo’s website. [1]

References

[1]
B. E. Pedersen, “Replace aliases with Netlify’s \_redirects · gohugoio/hugoDocs@c1ab989,” Jun. 20, 2017. https://github.com/gohugoio/hugoDocs/commit/c1ab9894e8292e0a74c43bbca2263b1fb3840f9e (accessed Jan. 14, 2023).