The default 502 page Caddy shows when an upstream is down is functional but tells the user nothing useful. The default 404 is text-only. The handle_errors directive lets you replace both with content matching your brand, and add structured handling per status code — different page for 5xx than 4xx, retry hints for 503, structured JSON for API endpoints. This article is the production setup we deploy for clients who want their errors to look like the rest of the site.
How to verify
A site with proper error handling responds like this:
curl -i https://app.example.com/does-not-exist # 404 with branded page
curl -i https://app.example.com/api/nonexistent # 404 with JSON
sudo systemctl stop my-app && curl -i https://app.example.com/ # 502 with branded page
sudo journalctl -u caddy --since '1m ago' | grep -i error
The 404 should return your custom HTML or JSON, not Caddy’s default. The 502 (with the upstream stopped) should return a maintenance-style page, not “Bad Gateway” plain text. The journal should show the error being captured by handle_errors.
What’s happening
Caddy’s request handling pipeline produces a response. If the response status is 4xx or 5xx and a handle_errors directive is configured, Caddy re-enters the handler chain with the error context available. Inside handle_errors, you can match on the status code, log the error, set custom headers, rewrite the request to a different path, and return a different response — typically a static HTML file or a JSON document.
The mechanism distinguishes between two error sources:
-
Errors from the application — the upstream returned a 5xx, or the request did not match any route (404). Caddy’s
handle_errorscaptures these and serves your custom page instead of relaying the upstream body. -
Errors from Caddy itself — the upstream is unreachable (502 Bad Gateway), the TLS handshake to the upstream failed, the request body was too large. These also flow through
handle_errors.
Both go through the same directive, but the placeholders available differ. {err.status_code} is set in both. {err.message} is set for Caddy-originated errors. {err.original_*} references the request before any rewrites.
The procedure
-
Add a basic error block for 404 and 5xx. Serve static HTML pages from a local directory:
app.example.com { reverse_proxy localhost:3000 handle_errors { @404 expression {err.status_code} == 404 handle @404 { rewrite * /404.html file_server { root /var/www/errors } } @5xx expression {err.status_code} >= 500 handle @5xx { rewrite * /5xx.html file_server { root /var/www/errors } } } }Caddy serves
/var/www/errors/404.htmlon any 404 from the upstream or any unmatched route. Same for 5xx with5xx.html. -
Different responses for HTML and API routes. An app that has both a UI and a JSON API:
app.example.com { handle /api/* { reverse_proxy localhost:3000 } handle { reverse_proxy localhost:3000 } handle_errors { @api path /api/* handle @api { header Content-Type application/json respond `{"error": "{err.status_text}", "code": {err.status_code}}` {err.status_code} } handle { rewrite * /{err.status_code}.html file_server { root /var/www/errors } } } }API requests get JSON, browser requests get HTML. The
{err.status_code}placeholder in the rewrite means you can have one file per status code (404.html,502.html,503.html) without listing each. -
Retry-after on 503. When a backend deploy returns 503 with
Retry-After, propagate it usefully:app.example.com { reverse_proxy localhost:3000 handle_errors { @503 expression {err.status_code} == 503 handle @503 { header Retry-After 30 rewrite * /maintenance.html file_server { root /var/www/errors } } handle { rewrite * /generic-error.html file_server { root /var/www/errors } } } } -
Log the error to a separate sink. Errors deserve a different log file than the access log:
app.example.com { reverse_proxy localhost:3000 log { output file /var/log/caddy/access.log } handle_errors { log_name error_log handle { rewrite * /{err.status_code}.html file_server { root /var/www/errors } } } log error_log { output file /var/log/caddy/error.log format json level WARN } }log_namedirects error-context log lines to the named logger; thelogblock at site level configures the sink. -
Per-error custom headers. When you want the error response to indicate “please retry on a different host” or “the resource has moved”:
handle_errors { @410 expression {err.status_code} == 410 handle @410 { header X-Resource-Status "permanently gone" respond "The resource you requested has been retired. See https://docs.example.com/migration." 410 } } -
Custom error pages with dynamic placeholders. Caddy supports templates in served HTML if you enable the templates directive:
handle_errors { templates rewrite * /{err.status_code}.html file_server { root /var/www/errors } }In
/var/www/errors/404.html:<!DOCTYPE html> <html lang="en"> <head><title>{{ "{{.OriginalRequest.URL.Path}}" }} not found</title></head> <body> <h1>That page does not exist.</h1> <p>The requested URL was {{ "{{.OriginalRequest.URL.Path}}" }}.</p> <p>Try <a href="/">our home page</a> or our <a href="/help">help center</a>.</p> </body> </html>The templates handler runs Go template syntax on the file before serving.
OriginalRequestis the request as it arrived, before any rewrites.
Operational notes
- The
handle_errorsblock runs for any non-2xx, non-3xx response from upstream handlers — including 401, 403, 404, 500, 502, 503, 504. Make sure your 401 (auth required) is not getting swallowed by a generic error page — match on status code explicitly andrespondwith the original challenge. - A
handle_errorsblock that has its own error (e.g., the 404.html file does not exist on disk) returns Caddy’s default error page — there is no recursive error handling. Verify the error files exist with a smoke test. - The
{err.status_code}placeholder is only available insidehandle_errors. Outside it,{http.response.status_code}exists but is set after the response is committed — too late to act on. - For multi-tenant SaaS, the error template should be sourced from the tenant’s branding rather than a global file. Use
{vars.tenant_id}(set earlier in the chain) to pick the right error directory. - Status code 499 (Nginx’s “client closed connection”) is sometimes set by Caddy too. Filter it from error logging if you do not care about clients that gave up — it is noise.
Stack Harbor configures error handling for client edges as part of the brand surface — custom pages match the site, error logs flow into the same pipeline as access logs, and the retry-after headers honor the actual deploy windows. If you have an edge that still serves Caddy’s default error pages and you want them aligned with the rest of the experience, this is the kind of work covered by our Managed Operations practice.