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.

1. The three kinds of block

{
	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.

2. Site addresses

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.

AddressMeaning
example.comHTTPS on the standard port, with a certificate obtained automatically
example.com, www.example.comOne block serving several names, sharing one certificate
http://example.comPlain HTTP only, no certificate, no redirect
localhost:8080A different port; the scheme still defaults to HTTPS for real hostnames
:8080Any host on that port
*.example.comA 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.

3. Global options

The global options block holds settings that span every site.

{
	email admin@example.com
	auto_https disable_redirects
	servers {
		timeouts {
			read_header 10s
		}
	}
}
  • email sets the contact address used when Caddy registers an ACME account with the certificate authority.
  • auto_https controls certificate automation and the redirect. Its values are off, disable_redirects, and disable_certs.
  • servers holds settings that belong to the listener rather than to one site, such as timeouts, max_header_size, and trusted_proxies.

4. Everyday directives

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
}

5. Routing: handle, handle_path, and route

These three constructs are the part of the Caddyfile that most often confuses newcomers.

  • handle creates a mutually exclusive group. The blocks are evaluated in the order they appear, the first matching block wins, and the rest are skipped.
  • handle_path behaves like handle but additionally strips the matched path prefix before the inner handlers run.
  • route evaluates 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.

6. Matchers

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
	}
}

7. Reuse: snippets, imports, and environment variables

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
}

8. Format, validate, and reload

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.

9. Frequent mistakes

MistakeWhat happensCorrection
Expecting file order to control handler orderThe adapter sorts directives by a built-in orderUse route when you need literal ordering
Using handle for two rules that should both applyOnly the first matching block runsUse route or separate top-level directives
Forgetting root * before file_serverThe file server serves the process working directorySet an explicit root
Expecting handle_path to keep the prefixThe prefix is removed before the inner handlers runUse handle when the upstream expects the full path
caddyfilesite blocksroutingsnippets

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:

  1. 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.
  2. Declare the site address. Writing app.example.com gives HTTPS with an automatic certificate, so no tls directive is needed.
  3. Use handle blocks 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.
  4. Use handle_path for the API, because the backend expects /orders rather than /api/orders, and handle_path removes the matched prefix before the inner handlers run.
  5. Use a plain handle block 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 with root * before file_server.
  6. Add the health endpoint as its own handle block with an exact path matcher, so it answers /healthz without reaching the file server.
  7. Apply the shared response headers through a snippet named common_headers, then import that snippet so the rule is defined once.
  8. Format and validate with caddy fmt and caddy 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.

Found an issue with this content?

Tell us what could be improved.