How to serve static HTML with status 503 (or 502) when web server is down?

1. Caddy version (caddy version):


2. How I run Caddy:

a. System environment:

Debian Buster

b. Command:

systemctl start caddy

c. Service/unit/compose file:

# caddy.service
# For using Caddy with a config file.
# Make sure the ExecStart and ExecReload commands are correct
# for your installation.
# See for instructions.
# WARNING: This service does not use the --resume flag, so if you
# use the API to make changes, they will be overwritten by the
# Caddyfile next time the service is restarted. If you intend to
# use Caddy's API to configure it, add the --resume flag to the
# `caddy run` command or use the caddy-api.service file instead.


ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile


d. My complete Caddyfile or JSON config:

	http_port   7080
	https_port  7443
} {
	@slashend path_regexp dir (.+)/$
	redir @slashend {http.regexp.dir.1} permanent
} {
	header strict-transport-security "max-age=63072000; includesubdomains; preload"
	redir{uri} permanent

3. The problem I’m having:

When the upstream server ( in my case) is down, I would like to serve a static HTML file with status code 503 (or alternatively 502). I have not been able to find any examples as to how this might be achieved with Caddy 2. I am new to Caddy with no experience in using it as anything other than a reverse proxy, but I believe that an example configuration would be of help to others too.

4. Error messages and/or full log output:


5. What I already tried:

I have spent over an hour searching online but could find no relevant Caddy 2 examples. The two most relevant finds are included below.

6. Links to relevant resources:

You can use the handle_errors directive for this:

Basically it’s a separate handler chain that gets invoked when Caddy emits an error (does not get invoked if a proxy writes a valid response, even if it’s a 4xx or 5xx status, by the way).

You can use an expression matcher to only handle status 502 which is the error Caddy emits when the backend is down:


Thanks for your help, Francis!

For other users, this addition to my Caddyfile seems to work:

handle_errors {
	@maintenance expression {http.error.status_code} == 502
	rewrite @maintenance maintenance.html
	root * /etc/caddy

This topic was automatically closed after 30 days. New replies are no longer allowed.