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

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, April 26, 2020

Follow me on Twitter as @mattiasgeniar

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.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.