Setting A Custom Output Format in Hugo for Netlify (or GitLab Page's) _redirects File was originally published on Farai's Codelab.
The_redirects
is used to specify redirects for Netlify. GitLab Pages also supports redirects, but none of the fancy Netlify things like splats, non 3xx HTTP codes and the like.
While Hugo supports custom output formats, it’s hard to understand the documentation which makes it work. Eventually, I came across a commit in the Hugo Docs repo where they set up an _redirects file.
With this and a few modifications, I was able to set up redirects. To do this:
- Create an
outputFormat
(named REDIR here) for the_redirects
file with mediatypetext/prs.netlify
1, baseName_rediects
and set isPlainText and notAlternative totrue
. - Add the media type mediatype with an array of suffixes containing an empty string and the delimiter set to empty string as well.
- Include the output format for the home page template alongside the other ones set2. The config file (
config.yaml
in my case) should have something like this now.
outputs:
home: ["HTML", "RSS", "REDIR"]
mediaTypes:
text/prs.netlify:
suffixes: [""]
delimiter: ""
outputFormats:
REDIR:
mediatype: text/prs.netlify
baseName: _redirects
isPlainText: true
notAlternative: true
- Finally, create a template for the
_redirects
file, which should be namedindex.<outputFormat_name>
(index.redir
in my case).
{{ range $p := .Site.Pages -}}
{{ range .Aliases }}
{{- printf "%s %s %d" . $p.RelPermalink ($p.Params.HTTPCode | default 301) }}
{{ end -}}
{{- end -}}
The ($p.Params.HTTPCode | default 301)
lets you set HTTPCode
in the front matter with the relevant 3xx redirection HTTP code. I also put a default at 301
for Moved Permanantly.
And this should do it. I don’t plan to stay on GitLab Pages very long so I’ll write another post for the platform I eventually move to. I hope to support be able to make more complex redirects by then.
-
It wasn’t
text/prs.netlify
to begin with but reading about MIME types, the vanity tree fornon publicly available products or experimental media types
makes sense here. It could have beenx.netlify
, but it’s discouraged. I might be overthinking this. ↩︎ -
Default for the home page is
["HTML", "RSS"]
. ↩︎
Thanks for reading. If you liked this post, support my work by sharing this post, refering me for a job, sponsoring me on Patreon, sending me money on Ko-fi, Paypal or Buy Me A Coffee. You could also use my affiliate links to buy something on Amazon or Namecheap. Note that I may earn a commisions through those links.
Got feedback? Email me at gandiyafarai + feedback at gmail dot com.
Top comments (0)