Set up a custom 404 page for static sites with Caddy 2

Here’s a quick example of setting up a custom 404 landing page if you use Caddy V2 to serve static sites, like this blog.

On Caddy 2#

ma.ttias.be {
    root * /var/www/html/ma.ttias.be/public
    file_server

    handle_errors {
        @404 {
            expression {http.error.status_code} == 404
        }
        rewrite @404 /404.html
        file_server
    }
}

The handle_errors directive allows you to create a new rule that mandates that every 404 page should be served /404.html.

This assumes you have a file called 404.html in your root directory (like I do here: ma.ttias.be/404.html ) that can get served.

On Caddy 1#

For completeness sake, here’s how it was done in Caddy V1.

ma.ttias.be {
    root /var/www/html/ma.ttias.be/public
    gzip

    errors /var/www/html/ma.ttias.be/logs/error.log {
        404 404.html
    }
}

As part of the errors directive, you could specify which file to serve as a 404-error.