The Caddyfile in Depth
Caddy as a Reverse Proxy showed how short a Caddyfile can be. Real sites grow: several apps on one domain, static files with an API, redirects, headers, error pages, shared snippets across sites. This lesson covers the parts of the Caddyfile that make larger configs manageable, and the one rule that surprises everyone: directive order is decided by Caddy, not by the order you write them.
Structure
{ # 1. global options (optional, must come first)
email ops@shop.example
}
(security_headers) { # 2. snippets: reusable blocks, used with "import"
header {
Strict-Transport-Security "max-age=31536000"
X-Content-Type-Options nosniff
-Server # a leading "-" removes a header
}
}
shop.example, www.shop.example { # 3. site blocks: one or more addresses
import security_headers
@api path /api/* # a named matcher
reverse_proxy @api 127.0.0.1:9000
file_server
}Inside a site, each line is a directive, optionally followed by a matcher that limits it to some requests:
| Matcher | Example |
|---|---|
| path (inline) | reverse_proxy /api/* 127.0.0.1:9000 |
* |
every request (the default) |
| named, several conditions ANDed | @admin { path /admin/*; remote_ip 10.0.0.0/8 } |
not |
@external not remote_ip private_ranges |
header, method, query, host, protocol |
@post method POST |
expression (CEL) |
@beta expression {cookie.beta} == "1" |
Placeholders insert request data: {path}, {query.page}, {header.User-Agent}, {remote_host}, and environment variables at load time with {$APP_PORT} or {$APP_PORT:9000} (with a default).
Directive order
Caddy sorts the directives in a site block into a fixed order (redir, rewrite, uri, try_files, … header, … handle_path, handle, route, … respond, reverse_proxy, php_fastcgi, file_server, …). So file_server written before reverse_proxy still runs after it. When you need explicit control:
handleblocks are mutually exclusive: only the first matchinghandleruns, and Caddy sortshandleblocks with path matchers by specificity (longer paths first). This is the closest thing to Nginx'slocation.handle_pathishandleplus stripping the matched prefix.routeruns the directives inside it in the order written.
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.end_headers(); self.wfile.write(f"api saw {self.path}\n".encode())
def log_message(self, *a): pass
HTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
mkdir -p site/docs && echo "docs index" > site/docs/index.html
{ echo "<h1>home</h1>"; for i in $(seq 40); do echo "<p>filler line $i</p>"; done; } > site/index.html # > 512 bytes: Caddy's encode minimum
cat > Caddyfile <<'EOF'
{
auto_https off
admin localhost:2019
}
(security_headers) {
header {
X-Content-Type-Options nosniff
-Server
}
}
:8080 {
import security_headers
root * site
encode zstd gzip
redir /old-docs/* /docs/{http.request.uri.path.1}/ 301
handle /api/admin/* {
respond "admin API is internal only" 403
}
handle_path /api/* {
reverse_proxy 127.0.0.1:9000
}
handle {
try_files {path} {path}/ /index.html
file_server
}
handle_errors {
respond "{err.status_code} {err.status_text}"
}
}
EOF
caddy fmt --overwrite Caddyfile && caddy validate --config Caddyfile 2>&1 | tail -1
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
caddy start --config Caddyfile > caddy.log 2>&1 && echo "caddy started"
show() { printf '%-22s -> %s\n' "$1" "$(curl -s -o out.txt -w '%{http_code} %{redirect_url}' "${@:2}" "127.0.0.1:8080$1" | sed 's/ $//') $(head -c 60 out.txt | head -1)"; }
show /
show /orders/42
show /docs/
show /old-docs/setup
show /api/links/7
show /api/admin/users
curl -s -D - -o /dev/null -H 'Accept-Encoding: zstd, gzip' 127.0.0.1:8080/ | grep -iE '^(content-encoding|x-content-type|server)' | tr -d '\r'
caddy stop > /dev/null 2>&1; kill %1Valid configuration
caddy started
/ -> 200 <h1>home</h1>
/orders/42 -> 200 <h1>home</h1>
/docs/ -> 200 docs index
/old-docs/setup -> 301 http://127.0.0.1:8080/docs/setup/
/api/links/7 -> 200 api saw /links/7
/api/admin/users -> 403 admin API is internal only
Content-Encoding: zstd
X-Content-Type-Options: nosniff
/api/admin/usersmatched bothhandleblocks, and the more specific/api/admin/*won although both are path matchers; the API never saw the request. Unlikehandle_path, plainhandlekeeps the path, which is fine for arespond./api/links/7reached the app as/links/7:handle_pathstripped/api./orders/42doesn't exist as a file, sotry_filesfell back toindex.html: the single-page-app pattern from try_files in one line. The{path}/candidate plays the role of Nginx's$uri/: without it,/docs/would also have fallen back to the home page instead of servingdocs/index.html.{http.request.uri.path.1}is the second path segment (counting from 0), so/old-docs/setupredirected to/docs/setup/.- The response was compressed with zstd, the first encoding in
encode zstd gzipthat the client accepts, and theServerheader was removed by the snippet.
Snippets with arguments and imports
Snippets accept arguments ({args[0]}), and import also takes files and globs, which is how teams keep one Caddyfile per app:
(proxy_app) {
reverse_proxy {args[0]} {
lb_policy least_conn
health_uri /healthz
health_interval 5s
}
}
import sites/*.caddy # each file holds one site block
linkly.example {
import proxy_app 10.0.1.11:8080 10.0.1.12:8080
}Formatting and adapting
caddy fmt --overwrite normalises indentation (tabs) and is worth running in CI with caddy fmt --diff to fail on unformatted files. caddy adapt --config Caddyfile --pretty prints the JSON that Caddy actually runs (the next lesson but one): when a directive seems ignored, check its position in the adapted routes.
Test yourself
A site block lists file_server first and reverse_proxy /api/* second. Which runs first for /api/x?
- file_server, because it is first
- reverse_proxy: Caddy orders directives by its built-in directive order, not by their position
- Both
- Neither
What is special about several handle blocks in one site?
- All of them run
- They are mutually exclusive: only the first matching one runs, with path-matched blocks sorted by specificity
- They run in reverse order
- They need names
How do you read the environment variable APP_PORT, with 9000 as default, in a Caddyfile?
$APP_PORT{$APP_PORT:9000}{env.APP_PORT}${APP_PORT-9000}