Caddy Configuration Examples
The examples on this page are complete configurations, not fragments. Each one can be copied into a file, validated, and started, and each one is annotated with the reason it is written the way it is. They are ordered from the simplest to the most involved, and every one of them starts with the same assumption: that you will validate before you deploy and reload rather than restart.
Save each example as Caddyfile, then check it and start it.
caddy validate --config Caddyfile
caddy run --config Caddyfile
For a real hostname, replace example.com with a name that resolves to the host, and Caddy will obtain the certificate on its own.
The baseline for serving a directory of files over HTTPS.
example.com {
root * /srv/www
encode zstd gzip
@assets path /assets/*
header @assets Cache-Control "public, max-age=31536000, immutable"
# Fingerprinted files can be cached forever; the entry document cannot.
@entry path / /index.html
header @entry Cache-Control "no-cache"
file_server
}
Two decisions are hidden in this file. The encode directive names zstd and gzip explicitly; the default would also be both, but naming them documents the intent and survives a change of defaults. And the two cache headers are deliberately different: files under /assets are assumed to have content hashes in their names, so they can be cached for a year, while the entry document must be revalidated so that a deploy is visible immediately.
A client-side application needs every unknown path to be served the same index.html, because the router lives in the browser.
example.com {
root * /srv/app
encode zstd gzip
# Let the browser know that the application handles its own routing.
@spa path /*
header @spa Cache-Control "no-cache"
# Serve the file if it exists, otherwise fall back to the entry document.
try_files {path} {path}/ /index.html
file_server
}
The try_files directive is what performs the fallback. Without it, a deep link such as /settings/profile would return a 404 from the file server, because no such file exists.
If the application needs the API on the same origin, put the API in its own handle block, which is mutually exclusive with the fallback.
example.com {
root * /srv/app
encode zstd gzip
@api path /api/*
handle @api {
reverse_proxy localhost:9000
}
handle {
try_files {path} {path}/ /index.html
file_server
}
}
api.example.com {
# The upstream should see the address it is bound to.
reverse_proxy localhost:9000 {
header_up Host {http.reverse_proxy.upstream.hostport}
header_up X-Real-IP {http.request.remote.host}
}
# A JSON API should not be compressed into a browser cache by accident.
header {
Cache-Control "no-store"
X-Content-Type-Options nosniff
}
request_body {
max_size 10MB
}
}
request_body with a max_size is worth setting on any endpoint that accepts uploads. Without a limit, the size of the body is bounded only by disk and memory.
Caddy proxies WebSocket upgrades without any special configuration. The upgrade handshake is an ordinary HTTP request with two extra headers, and the proxy handles it.
example.com {
@socket path /ws/*
reverse_proxy @socket localhost:9001
}
When the WebSocket lives on its own host, give it its own site block.
ws.example.com {
reverse_proxy localhost:9001
}
The things that break WebSockets are rarely in Caddy. They are an intermediary that strips the Upgrade header, an upstream idle timeout shorter than the heartbeat interval, or a proxy in front of Caddy that was never configured to forward the upgrade.
One Caddy process can serve many hostnames. Each site block is matched on the Host header, and they share the same set of listeners.
example.com {
respond "Main site" 200
}
docs.example.com {
root * /srv/docs
file_server
}
api.example.com {
reverse_proxy localhost:9000
}
# A catch-all for names that are not configured above.
:8080 {
respond "Unknown host" 404
}
Note that the first three blocks all live on the standard ports and are distinguished only by name, so the certificates for all three are issued from the same process and renewed on the same schedule.
example.com {
reverse_proxy backend-1:8080 backend-2:8080 backend-3:8080 {
lb_policy round_robin
lb_try_duration 10s
lb_retries 3
lb_try_interval 250ms
health_uri /healthz
health_interval 10s
health_timeout 5s
health_passes 2
health_fails 2
transport http {
read_timeout 30s
write_timeout 30s
}
}
}
lb_try_duration is the window in which a failing request may be retried against a different upstream. It has to be long enough to cover the time the backend needs to come back, otherwise the retry simply fails again against a backend that is still down.
For a primary and secondary arrangement, where traffic goes to the first upstream until it fails, use the first policy together with health checks.
reverse_proxy primary:8080 secondary:8080 {
lb_policy first
health_uri /healthz
health_interval 5s
health_fails 3
}
(security_headers) {
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options nosniff
X-Frame-Options SAMEORIGIN
Referrer-Policy strict-origin-when-cross-origin
Permissions-Policy "geolocation=(), microphone=()"
-Server
}
}
example.com {
import security_headers
respond "ok" 200
}
As a snippet this is applied once and imported everywhere, which is the only practical way to guarantee that every site in a deployment has the same baseline.
When the application is down but the site must stay up, serve a static page and keep the status code honest.
example.com {
root * /srv/maintenance
@maintenance {
not path /maintenance.html /healthz
}
respond @maintenance "We are performing maintenance. Back shortly." 503
handle /healthz {
respond "ok" 200
}
}
Returning 503 rather than 200 is the important part. A maintenance page that answers with 200 will tell monitoring systems and search engines that everything is fine.
The same idea works for errors from the application, using handle_errors.
example.com {
handle_errors {
@500 expression {err.status_code} >= 500
rewrite @500 /error.html
file_server
}
reverse_proxy localhost:9000
}
example.com {
log {
output file /var/log/caddy/example.com.access.log {
roll_size 100mb
roll_keep 10
roll_keep_for 720h
}
format json
}
respond "ok" 200
}
Rotation is on by default, and the settings above keep ten rolled files for thirty days. The format json choice makes the file directly consumable by a log shipper, and log_skip is worth adding for health checks so that they do not dominate the volume.
services:
caddy:
image: caddy:2
restart: unless-stopped
ports:
- "80:80"
- "443:443"
- "443:443/udp"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data
- caddy_config:/config
environment:
- ACME_EMAIL=admin@example.com
app:
image: nginx:alpine
restart: unless-stopped
expose:
- "80"
volumes:
caddy_data:
caddy_config:
The two named volumes are the ones that matter. Without them, every container restart creates a new ACME account and re-issues every certificate, which will eventually hit the rate limit of the certificate authority.
A few patterns tie the examples together.
Use snippets for anything that appears twice. A header block that is written in twenty site blocks will drift, and the twentieth one will be the one that is wrong.
Name your matchers. A named matcher reads better than an inline condition, and it can be shared by several directives.
Keep the global options in one file. Global options are a property of the process. Splitting them across site files makes the effective configuration depend on which files happen to be imported.
Validate before you reload. caddy validate provisions the modules without starting the server, which catches errors that only appear at provision time, such as a certificate file that does not exist.
caddy validate --config Caddyfile && caddy reload --config Caddyfile
Approach:
The task is to serve a single-page application from one hostname, with its API on the same origin, without giving up HTTPS. The interesting decision is not any individual directive but the shape of the routing, because a client-side router and a server-side API both answer on the same host and must not shadow each other. Getting that shape right means the site works for deep links and for API calls with no special cases.
Steps:
- Write the global options first, so that the ACME contact address and the admin endpoint are settled before any site block depends on them.
- Decide the routing shape. The API prefix is matched by a named matcher and handled in its own
handleblock; everything else falls into a secondhandleblock that serves the application. - In the application block, set the root and use
try_filesso that an unknown path is answered with the entry document instead of a 404, which is what makes deep links work. - Add
encodefor compression, and setCache-Controlso that the entry document is revalidated while fingerprinted assets are cached for a long time. - In the API block, proxy to the backend and rewrite the Host header, because most applications validate the Host and will reject a request carrying the public name.
- Add a snippet with the security headers, so that every site in the deployment gets the same baseline.
- Validate the file, which provisions the modules without starting the server and catches errors that only surface at provision time.
- Reload rather than restart, so that the running process picks up the change without a window in which the site is not serving.
Answer:
The finished Caddyfile looks like this.
{
email admin@example.com
}
(security_headers) {
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options nosniff
X-Frame-Options SAMEORIGIN
-Server
}
}
example.com {
root * /srv/app
encode zstd gzip
import security_headers
@entry path / /index.html
header @entry Cache-Control "no-cache"
@assets path /assets/*
header @assets Cache-Control "public, max-age=31536000, immutable"
@api path /api/*
handle @api {
reverse_proxy localhost:9000 {
header_up Host {http.reverse_proxy.upstream.hostport}
}
}
handle {
try_files {path} {path}/ /index.html
file_server
}
}And it is deployed with two commands, neither of which interrupts traffic.
caddy validate --config Caddyfile && caddy reload --config CaddyfileThe result is that https://example.com/ serves the application, https://example.com/settings/profile serves the same entry document so the browser-side router can take over, https://example.com/api/orders is proxied to the backend with a Host header the backend accepts, and the certificate is issued and renewed by Caddy without any further action.
