Caddy Security Configuration

Caddy is secure by default in the ways that matter most: it refuses to serve TLS versions that are known to be broken, it will not hand out a certificate for a name it cannot prove it controls, and it runs as an unprivileged account under a package-managed service. Everything else is your responsibility. By the end of this page you will be able to add the response headers that browsers expect from a hardened site, restrict access by IP address, cap request sizes and header volume, put authentication in front of a site, and keep secrets out of the configuration file.

1. The baseline you already have

Before adding anything, know what Caddy does for free:

  • TLS 1.2 and 1.3 only, with modern cipher suites, and no support for SSLv3 or TLS 1.0/1.1.
  • Automatic HTTPS, so no site is accidentally published over plain HTTP.
  • HTTP to HTTPS redirection on port 80, with only the ACME challenge path served in the clear.
  • No directory listing by default; the file server will not browse a directory unless you ask it to.
  • An unprivileged service account and a data directory that only that account can read.

Security headers are the part that is not automatic. Caddy will not send Strict-Transport-Security or a Content-Security-Policy unless you ask it to.

2. Security response headers

The header directive sets, appends, or removes response headers. Setting a field without a prefix overwrites it.

example.com {
	header {
		Strict-Transport-Security "max-age=31536000; includeSubDomains"
		X-Content-Type-Options "nosniff"
		X-Frame-Options "DENY"
		Referrer-Policy "strict-origin-when-cross-origin"
		Permissions-Policy "geolocation=(), microphone=()"
		-Server
	}
	respond "hardened" 200
}

A few rules keep this safe:

  • Send HSTS only over HTTPS. Because the header tells the browser to refuse plain HTTP for a year, enable it only once you are certain every subdomain is served over HTTPS. includeSubDomains extends that promise to all of them.
  • Do not remove X-Content-Type-Options. It is the cheapest protection against a browser guessing a content type and executing a file as a script.
  • Test a Content-Security-Policy in report-only mode first. A wrong policy breaks the site completely, and Content-Security-Policy-Report-Only tells you what would have been blocked without blocking it.

3. Access control by IP address

The remote_ip matcher tests the client address, and it accepts both single addresses and CIDR ranges.

example.com {
	@denied {
		remote_ip 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
	}
	handle @denied {
		respond "Forbidden" 403
	}
	handle {
		reverse_proxy localhost:9000
	}
}

For an allowlist, name the permitted ranges and let the fallback block reject everything else.

example.com {
	@allowed remote_ip 203.0.113.0/24 198.51.100.7
	handle @allowed {
		reverse_proxy localhost:9000
	}
	handle {
		respond "Not allowed" 403
	}
}

An allowlist is far stronger than a denylist, because it fails closed. A denylist only blocks the addresses you thought of.

4. Limits on requests

Two limits matter most: how much body a client may upload, and how much header data Caddy will parse at all.

{
	servers {
		max_header_size 16KiB
		timeouts {
			read_header 10s
			read_body 30s
		}
	}
}

example.com {
	request_body {
		max_size 10MB
	}
	reverse_proxy localhost:9000
}

max_header_size defaults to 16KiB, and a request that exceeds it is answered with status 431. read_header bounds how long a client may take to send its headers, which is the classic slowloris defence. The request_body directive caps the upload size and answers anything larger with status 413.

5. Authentication

basic_auth protects a site with HTTP Basic Authentication. Passwords are stored as hashes, never in the clear.

caddy hash-password --plaintext 'correct horse battery staple' --algorithm argon2id
example.com {
	basic_auth {
		admin {env.ADMIN_PASSWORD_HASH}
	}
	respond "secret area" 200
}

The username and the hash may both use env placeholders, so the hash can live in a file that is readable only by the service account rather than inside the Caddyfile. The argon2id algorithm is the recommended one; bcrypt is the default and remains acceptable.

For anything more elaborate, forward_auth delegates the decision to an external authentication service such as Authelia, OAuth2 Proxy, or your own gateway.

example.com {
	forward_auth authelia:9091 {
		uri /api/verify?rd=https://auth.example.com
		copy_headers Remote-User Remote-Groups
	}
	reverse_proxy localhost:9000
}

Caddy sends a request to the authentication service with the original URI rewritten. A 2xx response grants access and copies the listed headers into the original request; any other status is passed straight back to the client, which is how a redirect to a login page reaches the browser.

6. Rate limiting

Caddy has no built-in rate limiter directive, so there are two honest options.

The first is a plugin. The mholt/caddy-ratelimit module adds a rate_limit directive that defines named zones, each zone being one limit of so many events per time window.

xcaddy build --with github.com/mholt/caddy-ratelimit
example.com {
	rate_limit {
		zone per_ip {
			key {http.request.remote.host}
			window 1m
			events 10
		}
	}
	reverse_proxy localhost:9000
}

The key decides how requests are grouped: a placeholder creates one bucket per client, while a static value creates a single shared bucket. The plugin uses a sliding window, so a client that stays just under the limit never gets a clean restart, and it sets a Retry-After header on the 429 responses it generates. By default the rate_limit directive is ordered before basic_auth, so the limit applies before the password check.

The second is to delegate. A gateway or an authentication service that already counts requests can be placed in front of Caddy with forward_auth, and it answers with status 429 when the caller is over the limit. This keeps Caddy free of extra modules and works well when the limit must be shared across several services.

7. TLS hardening

Caddy’s TLS defaults are already strong. You normally only need to set them explicitly so that an upgrade cannot change them underneath you.

example.com {
	tls {
		protocols tls1.2 tls1.3
		key_type p256
	}
	respond "hardened tls" 200
}

p256 keys are smaller and faster than RSA keys while remaining universally supported. Pinning the protocols explicitly protects against a future default change, which is what compliance rules often require.

8. Trusted proxies and the client address

The address Caddy sees is the address of whoever connected to it, which behind a load balancer is the load balancer. X-Forwarded-For is a client-supplied header, so trusting it blindly lets any client claim any address.

{
	servers {
		trusted_proxies static private_ranges 203.0.113.0/24
	}
}

Only requests that arrive from a trusted range get their real client address parsed from X-Forwarded-For. Requests from anywhere else keep the transport-level address. This matters for logging, for the remote_ip matcher above, and for every access decision you make on the basis of a client address.

9. Keeping secrets out of the configuration

  • Use environment variables for credentials. Reference them with {$NAME} or {env.NAME} and load them from a file that only the service account can read.
  • Keep the Caddyfile readable by the service account only. A configuration that contains a database password should not be world-readable.
  • Protect the data directory. It holds private keys for every certificate the server has issued.
sudo chown caddy:caddy /etc/caddy/Caddyfile
sudo chmod 640 /etc/caddy/Caddyfile
caddy run --config /etc/caddy/Caddyfile --envfile /etc/caddy/env

10. Common mistakes

MistakeWhat happensCorrection
Sending HSTS before every subdomain is on HTTPSA subdomain becomes unreachableStart with a short max-age
Allowing 0.0.0.0/0 in an allowlistThe allowlist protects nothingList the real ranges
Trusting X-Forwarded-For from any sourceClients spoof their own addressConfigure trusted_proxies
Storing plaintext passwordsA config leak becomes an account leakUse caddy hash-password
Raising read_body without a max_sizeDisk and memory can be exhaustedKeep both limits
security hardeningaccess controlsecurity headersrate limiting

Approach:

The requirement is an internal administration site that must not be reachable from the public internet, hardened with the standard response headers, protected by an IP allowlist and a password, and shielded from oversized or slow requests. Because the site is internal, the allowlist is the primary control and the password is the second layer, not the only one.

Steps:

  1. Put the IP allowlist first, using the remote_ip matcher and a handle block that answers with status 403 for anything outside the two office ranges.
  2. Put the password check behind it, with basic_auth using a hash generated by caddy hash-password and loaded from an environment variable so the hash never sits in the Caddyfile.
  3. Add the standard response headers with the header directive, including HSTS, but only after confirming that every subdomain is already served over HTTPS.
  4. Cap the request body with request_body { max_size } and keep the default max_header_size, so an oversized upload or a huge header block is rejected before it is processed.
  5. Set read_header in the servers block to bound how long a client may take to send its headers, which closes the slowloris path.
  6. Configure trusted_proxies so that the remote_ip matcher sees the real client address when the site is behind a load balancer, and no address at all when it is not.
  7. Tighten the permissions on the Caddyfile and the environment file, then verify the result with an external request rather than from the server itself.

Answer:

The hardened configuration is:

{
	servers {
		max_header_size 16KiB
		timeouts {
			read_header 10s
		}
		trusted_proxies static 203.0.113.0/24
	}
}

admin.example.com {
	@allowed remote_ip 203.0.113.0/24 198.51.100.0/24
	handle @allowed {
		basic_auth {
			admin {env.ADMIN_PASSWORD_HASH}
		}
		header {
			Strict-Transport-Security "max-age=31536000; includeSubDomains"
			X-Content-Type-Options "nosniff"
			X-Frame-Options "DENY"
			Referrer-Policy "strict-origin-when-cross-origin"
			-Server
		}
		request_body {
			max_size 2MB
		}
		reverse_proxy localhost:9000
	}
	handle {
		respond "Not allowed" 403
	}
}

With this configuration, a request from an address outside the two allowlisted ranges is answered with 403 before any application code runs, a request from inside them still requires the admin password, every response carries the hardening headers, an upload larger than 2MB is rejected with status 413, and a client that stalls during the header phase is disconnected after ten seconds.

Found an issue with this content?

Tell us what could be improved.