Custom Error Pages in Hugo

in   Hugo  

Hugo is a well known static-site generator, which is what I’m using to generate this website. I also like to have a custom error page for different HTTP errors, such as 404, 403, etc., and I like them to be in the same style as the rest of the website.

While I have customized the page so that I can have a slightly different template for the error page, the instructions on this page apply to most themes, and can be used to generate error pages easily.

The following snippet shows the error/single.html template, which is used to generate the error page.

{{ define main }}
<h4>{{ .Title }}</h4>
{{ end }}

This file contains the actual error page.

title: "404 Page Not Found"

Finally, we want to avoid generating a list page, and instead redirect the generated /error/index.html to the home page

<!doctype html>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta http-equiv="refresh" content="0; url={{ .Site.BaseURL }}">

It is still possible to generate a normal-style page, without the single.html template - this will use the theme’s default single post template, and you can enter whatever you want in the error page. However, the list.html template will still be required.

To add this to your webserver, you’ll need to add the following lines in your server configuration.

error_page 404 /error/404/index.html
# In your sites .htaccess file
ErrorDocument 404 /error/404/index.html