Customizing Hugo’s 404 Page

The default 404 page is just plain text. Today I found an adorable logo collection, ServiceLogos, and casually brought it over.

Steps

Modify the Nginx configuration

Add the following site configuration to Nginx:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    # index.html fallback
    location / {
        try_files $uri $uri/ =404;
    }

    # Custom error pages
    error_page 404 /404.html;
    error_page 403 /403.html;
    location ~ ^/(404|403)\.html$ {
        root /www/public;
        internal;
    }

This Nginx configuration consists of several parts, which I will explain one by one below:

  • index.html fallback: This part defines how Nginx handles requests to the root directory.

    • location / { ... } specifies the rules for handling requests to the root directory and its subdirectories.
    • try_files $uri $uri/ =404; tries in the following order: first it looks for a file matching the request URI; if not found, it tries to handle the request as a directory; if that also fails, it returns a 404 error (page not found).

    This means that if the requested file or directory does not exist, Nginx will return a 404 error.

  • Custom error pages: This part defines the paths and handling of the custom error pages.

    • error_page 404 /404.html; uses /404.html as the error page when a 404 error (page not found) occurs.
    • error_page 403 /403.html; uses /403.html as the error page when a 403 error (access forbidden) occurs.

    This means that when the requested page does not exist or the request is denied, Nginx will display the designated error page accordingly.

  • Handling rules for specific error pages:

    • location ~ ^/(404|403)\.html$ { ... } uses a regular expression to match the path and capture requests for 404.html or 403.html.
    • root /www/public; specifies the root directory where these error pages reside.
    • The internal; directive means these pages can only be processed by Nginx as the result of internal requests. That is, they cannot be accessed by directly entering these URLs in a browser; they are only rendered through Nginx’s internal redirect when a 404 or 403 error occurs.

Modify the 404 page template

Copy the template to layouts

1
cp themes/PaperMod/layouts/404.html layouts

Content:

1
2
3
4
5
{{- define "main" }}
<div class="not-found" style="text-align: center;">
    <img src="/img/NotFound.png" alt="404Notfound">
</div>
{{- end }}{{/* end main */ -}}

References