Lesson 2 of 9 · 24m
Caddyfile Patterns That Don't Rot
Site blocks, matchers, snippets, imports, environment variables, and the ordering traps that make simple files behave surprisingly.
A small Caddyfile reads so cleanly that people assume it is a toy format. Then they add three redirects, an API exception, a maintenance page, and a bot rule — and discover that the format is simple but the request pipeline still needs architecture. Treat the Caddyfile as a concise interface to a routing engine, not as a list of commands executed top to bottom.
The file has structure, not just lines
{
email ops@sudosecurity.org
}
(common-security) {
header {
-Server
X-Content-Type-Options nosniff
Referrer-Policy strict-origin-when-cross-origin
}
}
app.sudosecurity.org {
import common-security
root * /srv/app/public
encode zstd gzip
@api path /api/*
reverse_proxy @api 127.0.0.1:8080
file_server
}The top braces are the global options block. (common-security) is a reusable snippet copied in by import. Named matchers such as @api keep boolean request logic out of the directive itself, which matters once conditions stop being trivial.
Directive order is sorted unless you control it
This is the trap that bites experienced nginx users first. Many directives have a defined relative order; they are not simply executed in visual order. redir, rewrite, reverse_proxy, and file_server can interact in ways the layout does not make obvious. When exact order matters, use route:
route {
rewrite /old-docs /docs
reverse_proxy /api/* 127.0.0.1:8080
file_server
}Inside route, directives execute in the order written. If you ever say "but I put it above the proxy," stop guessing and make the order explicit.
handle is for routing branches
handle /api/* {
reverse_proxy 127.0.0.1:8080
}
handle {
root * /srv/app/public
try_files {path} /index.html
file_server
}handle blocks are mutually exclusive branches. Use handle_path when the prefix should be stripped before the backend sees it. The difference sounds trivial until an upstream expects /login and receives /api/login.
Environment values are data, not structure
app.sudosecurity.org {
reverse_proxy {$UPSTREAM:127.0.0.1:8080}
}The placeholder reads UPSTREAM from the environment, with the loopback upstream as default. Use that for addresses, ports, and small environment differences — not for generating radically different architectures. If staging and production have different route shapes, say so explicitly instead of hiding them behind substitution magic.
Field notes
- Run
caddy fmt --overwrite Caddyfile; canonical formatting makes diffs smaller and reveals nesting mistakes. - Run
caddy validate --config Caddyfilebefore reload. Validation catches syntax, not bad upstreams or DNS. - Prefer named matchers over repeating long
pathexpressions inline; they read like policy rather than punctuation. - Use
caddy adapt --config Caddyfile --prettywhenever the written shape and observed behavior disagree.
Was this lesson helpful?