Caddy Basic Configuration
The Caddyfile is a small configuration language that Caddy translates into its native JSON form. Almost everything you need fits into three ideas: a site block that binds addresses to a set of directives, a global options block that configures the server as a whole, and the directives inside a site block that decide what happens to each request. By the end of this page you will be able to write a Caddyfile from scratch, choose correctly between handle, handle_path, and route, reuse configuration with snippets, and validate and reload changes without dropping connections.
{
email admin@example.com
}
example.com {
root * /srv/www
file_server
}
The global options block sits at the top of the file and may appear only once. A snippet is a named block in parentheses, pulled into a site block with import. Site blocks are the ordinary case: one or more addresses on the left, directives on the right.
The address on the left of a site block tells Caddy which hostnames and ports the block answers for. Caddy parses it into a scheme, a host, and a port.
| Address | Meaning |
|---|---|
example.com | HTTPS on the standard port, with a certificate obtained automatically |
example.com, www.example.com | One block serving several names, sharing one certificate |
http://example.com | Plain HTTP only, no certificate, no redirect |
localhost:8080 | A different port; the scheme still defaults to HTTPS for real hostnames |
:8080 | Any host on that port |
*.example.com | A wildcard name, which requires a wildcard certificate |
Because the scheme defaults to HTTPS whenever the host is a real domain, a plain example.com block already gets a certificate and an HTTP-to-HTTPS redirect on port 80. You only need http:// when you deliberately want unencrypted traffic.
The global options block holds settings that span every site.
{
email admin@example.com
auto_https disable_redirects
servers {
timeouts {
read_header 10s
}
}
}
emailsets the contact address used when Caddy registers an ACME account with the certificate authority.auto_httpscontrols certificate automation and the redirect. Its values areoff,disable_redirects, anddisable_certs.serversholds settings that belong to the listener rather than to one site, such as timeouts,max_header_size, andtrusted_proxies.
4.1 Serving files
root sets the document root and file_server serves what is found there. The precompressed option serves a .br or .gz sibling file when the client accepts that encoding, so assets can be compressed at build time instead of on every request.
example.com {
root * /srv/www
file_server {
index index.html
hide .git .env
precompressed br gzip
}
}
4.2 Responses and redirects
respond short-circuits the request and writes a fixed body, which makes it the fastest way to build a landing page or a health endpoint.
example.com {
redir /old-path /new-path 301
respond "It works" 200
}
4.3 Rewriting the URI
The uri directive changes the request path before routing continues. It supports strip_prefix, strip_suffix, replace, path_regexp, and query. The rewrite directive is the blunter tool: it resets the request to a completely different target and is treated as an internal redirect.
example.com {
uri strip_prefix /products
reverse_proxy localhost:9000
}
4.4 Falling back to an application
try_files serves a static file when it exists and falls back to an application otherwise.
example.com {
root * /srv/www
try_files {path} {path}/ /index.php
file_server
}
These three constructs are the part of the Caddyfile that most often confuses newcomers.
handlecreates a mutually exclusive group. The blocks are evaluated in the order they appear, the first matching block wins, and the rest are skipped.handle_pathbehaves likehandlebut additionally strips the matched path prefix before the inner handlers run.routeevaluates its contents in the written order, with no sorting and no exclusivity, so several handlers can run for one request.
example.com {
handle_path /api/* {
reverse_proxy localhost:9000
}
handle {
root * /srv/www
file_server
}
}
A request for /api/orders matches the first block, the prefix /api is stripped, and the upstream receives /orders. A request for /about falls through to the second block and is served from disk. Use route when you need literal ordering, for example when a header must be set before a response is written.
A named matcher is a reusable condition, declared with an at-sign and a name, then referenced by name in any directive. Common matchers include path, method, header, header_regexp, remote_ip, host, query, expression, and file.
example.com {
@api {
path /api/*
method GET POST
}
handle @api {
reverse_proxy localhost:9000
}
}
Snippets name a block of directives so it can be imported wherever it is needed. import also pulls in other files, and glob patterns are supported; the path is always relative to the file containing the import line. Environment variables are substituted at parse time with the {$NAME} syntax, and an explicit environment file can be loaded at startup with caddy run --envfile.
(common_headers) {
header {
X-Content-Type-Options nosniff
Referrer-Policy strict-origin-when-cross-origin
}
}
example.com {
import common_headers
import /etc/caddy/sites/*.caddy
respond "ok" 200
}
Never hand-tune whitespace. Caddy ships a formatter, a validator, and a reloader.
caddy fmt --overwrite /etc/caddy/Caddyfile
caddy validate --config /etc/caddy/Caddyfile
caddy adapt --config /etc/caddy/Caddyfile --pretty
sudo systemctl reload caddy
caddy fmt rewrites the file with canonical formatting, caddy validate parses and provisions the config without starting anything, and caddy adapt shows the JSON that the Caddyfile adapter produces. The reload path is graceful: the new configuration is validated and loaded while the old one stays alive until in-flight requests finish.
| Mistake | What happens | Correction |
|---|---|---|
| Expecting file order to control handler order | The adapter sorts directives by a built-in order | Use route when you need literal ordering |
Using handle for two rules that should both apply | Only the first matching block runs | Use route or separate top-level directives |
Forgetting root * before file_server | The file server serves the process working directory | Set an explicit root |
Expecting handle_path to keep the prefix | The prefix is removed before the inner handlers run | Use handle when the upstream expects the full path |
Approach:
The request is a single-site configuration that serves a static directory, exposes a health endpoint, proxies an API prefix to a backend, and sets a couple of response headers. The interesting part is not the individual directives but choosing the right routing construct, because handle, handle_path, and route behave differently when two rules could match the same request.
Steps:
- Start with the global options block and set the ACME contact address, because that value is used for the account Caddy registers with the certificate authority.
- Declare the site address. Writing
app.example.comgives HTTPS with an automatic certificate, so notlsdirective is needed. - Use
handleblocks to create mutually exclusive routes, since the API rule and the static rule must never both apply. Put the API rule first so it is evaluated first. - Use
handle_pathfor the API, because the backend expects/ordersrather than/api/orders, andhandle_pathremoves the matched prefix before the inner handlers run. - Use a plain
handleblock with no matcher as the final route, so it acts as the catch-all for every request the API rule did not match, and set the document root withroot *beforefile_server. - Add the health endpoint as its own
handleblock with an exact path matcher, so it answers/healthzwithout reaching the file server. - Apply the shared response headers through a snippet named
common_headers, then import that snippet so the rule is defined once. - Format and validate with
caddy fmtandcaddy validate, then reload the service so the change is applied without dropping connections.
Answer:
The finished Caddyfile is:
{
email admin@example.com
}
(common_headers) {
header {
X-Content-Type-Options nosniff
Referrer-Policy strict-origin-when-cross-origin
}
}
app.example.com {
import common_headers
handle /healthz {
respond "ok" 200
}
handle_path /api/* {
reverse_proxy localhost:9000
}
handle {
root * /srv/www
file_server
}
}With this file, /healthz returns ok with status 200, /api/orders is forwarded to http://localhost:9000/orders with the prefix removed, and any other request such as /about is served from /srv/www. The site is served over HTTPS with an automatically managed certificate, and caddy validate reports the configuration as valid.
