Caddy guide · Content-Security-Policy

How to set Content-Security-Policy on Caddy

Add a Content-Security-Policy header in Caddy, reuse it with a snippet, override it on one path and avoid a second policy behind reverse_proxy. Tested Caddyfiles.

  • By
  • Updated
  • 5 min read
  • Tested on Caddy 2.9, 2.10 and 2.11
$ curl -sI https://example.com/missing
status
HTTP/2 404
server
Caddy
content-security-policy
default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'

Present on error pages too

In short5 points
  • Add header Content-Security-Policy "…" to the site block. Caddy sends it on error pages too, including 404s from file_server and responses from handle_errors.
  • Behind reverse_proxy or php_fastcgi, a plain header line adds a second policy next to the application's. Remove the application's with header_down -Content-Security-Policy inside the proxy block.
  • A header /embed/* override runs before the site-wide header line and gets overwritten. Make the site-wide value a default with ?Content-Security-Policy.
  • Put the policy in a snippet and import it in every site block. Quote values that contain double quotes with backticks.
  • Start with Content-Security-Policy-Report-Only and a Reporting-Endpoints header, then rename the header once violations stop.

The short answer

Add this line to the site block in your Caddyfile, check the configuration and reload Caddy:

Caddyfile
example.com {
	root * /var/www/example
	file_server
	header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"
}
Shell
caddy validate --config /etc/caddy/Caddyfile && sudo systemctl reload caddy

Caddy sends the header on error pages without any extra flag. Every snippet below was run on Caddy 2.9, 2.10 and 2.11 and checked with curl, on a page, a 404 and a proxied application.

If you have not chosen a policy yet, read what each CSP directive does first. The policy above suits a site that loads everything from its own domain and has no inline scripts.

Before you start

Find every header directive and every proxy in your Caddyfile:

Shell
grep -nE "header|reverse_proxy|php_fastcgi|import" /etc/caddy/Caddyfile

To see what Caddy actually runs, including the order it chose for your directives, convert the Caddyfile to JSON:

Shell
caddy adapt --config /etc/caddy/Caddyfile --pretty

Wrap the policy in double quotes and keep the single quotes around keywords like 'self'. When a value contains double quotes, wrap it in backticks instead. An unescaped double quote does not cause an error: in our test, Caddy split the value in two, read it as a find-and-replace on an absent header, and sent nothing.

Step 1: ship the policy in report-only mode

Report-only mode applies the policy without blocking anything. Pair it with a Reporting-Endpoints header so violations from real visitors reach you:

Caddyfile
example.com {
	# ...
	header {
		Reporting-Endpoints `csp-endpoint="https://example.com/csp-reports"`
		Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; report-to csp-endpoint; report-uri https://example.com/csp-reports"
	}
}

Our test returned Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports" with its double quotes intact. report-to sends reports through the Reporting API; keep report-uri as a fallback for older browsers. Browse your main pages with the developer console open, fix what is reported, and let real traffic run against the policy for a few days.

Step 2: reuse it with a snippet

A snippet keeps one copy of your security headers for every site block:

Caddyfile
(security-headers) {
	header {
		Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"
	}
}

example.com {
	root * /var/www/example
	file_server
	import security-headers
}

The snippet must come before the site blocks that import it; otherwise caddy validate fails with File to import not found. Our test returned the policy on the page and on a 404.

Unlike Nginx and Apache, Caddy needed no flag to keep the header on errors. In our test it was present on 404s from file_server, with Caddy’s default error response and with a handle_errors block that writes its own body.

Step 3: a different policy for one path

To let a partner frame /embed/, the obvious Caddyfile does not work:

Caddyfile
example.com {
	# ...
	header Content-Security-Policy "default-src 'self'; frame-ancestors 'none'"
	header /embed/* Content-Security-Policy "default-src 'self'; frame-ancestors 'self' https://partner.example"
}

Our test returned frame-ancestors 'none' for /embed/ as well. Caddy sorts directives of the same name by matcher: the most specific path first, and the directive without a matcher last. The site-wide line runs after the /embed/* line and overwrites it.

Prefix the site-wide line with ?. It then sets the header only if no other line did:

Caddyfile
example.com {
	# ...
	header ?Content-Security-Policy "default-src 'self'; frame-ancestors 'none'"
	header /embed/* Content-Security-Policy "default-src 'self'; frame-ancestors 'self' https://partner.example"
}

Our test returned the /embed/ policy for /embed/ and for a 404 under it, and the site-wide policy everywhere else. Do not use ? in front of reverse_proxy, though: see the next sections.

Step 4: enforce the policy

When the reports have gone quiet, rename the header from Content-Security-Policy-Report-Only to Content-Security-Policy. Keep the reporting directives: they now report blocked resources.

Caddyfile
header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests; report-to csp-endpoint; report-uri https://example.com/csp-reports"

Hashes and nonces

A static site cannot use nonces, because the same HTML is served to everyone. List the hash of each inline script instead. The hash covers the exact text between <script> and </script>, whitespace included:

Shell
printf '%s' "console.log('ok')" | openssl sha256 -binary | openssl base64
# z45zR03J8fjhB+XZI75tfFNuEulXqY6Qn0ZMYwFwVws=
Caddyfile
header Content-Security-Policy "script-src 'self' 'sha256-z45zR03J8fjhB+XZI75tfFNuEulXqY6Qn0ZMYwFwVws='; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"

For a dynamic site, let the application generate a fresh nonce for each response, write it into the HTML and send the header. Then keep Caddy from adding or replacing it (next section).

Behind reverse_proxy or php_fastcgi

A plain header line runs before the proxy. When the application sends its own CSP, Caddy keeps both. Our test, with an application sending default-src *:

HTTP
HTTP/1.1 200 OK
Content-Security-Policy: default-src 'self'
Content-Security-Policy: default-src *

Browsers enforce both policies, so pages break in confusing ways. Decide who owns the policy. If it is Caddy, remove the application’s header as the response comes back from the proxy:

Caddyfile
example.com {
	header Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
	reverse_proxy 127.0.0.1:8080 {
		header_down -Content-Security-Policy
	}
}

Our test returned a single policy, Caddy’s, on the application’s pages and 404s, and on Caddy’s 502 when the application was down. php_fastcgi is built on the same proxy, so the same applies to PHP.

Prefixing the field with >, as in header >Content-Security-Policy …, also replaced the application’s value, but it defers the header until the application writes the response. When the application was down, Caddy’s 502 had no policy at all. Use header_down instead.

The ? prefix from step 3 does the opposite: it only sets the header when none exists, so the application’s policy wins. In our test, header ?Content-Security-Policy in front of reverse_proxy returned only the application’s default-src *. Use ? only when the application should own the policy.

Only on HTML responses

The policy only matters on documents. To skip it on images, scripts and stylesheets, add a response matcher:

Caddyfile
header {
	Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
	match {
		header Content-Type text/html*
	}
}

Our test sent the header on the home page and not on app.js. Caddy’s default 404 response has no Content-Type, so it got no policy either, which is harmless for an empty body. Sending the header everywhere is simpler, so this is optional.

Verify it

Check the header on a normal page and on an error page:

Shell
curl -sI https://example.com/ | grep -i content-security-policy
curl -sI https://example.com/does-not-exist | grep -i content-security-policy

Count the headers to catch duplicates. The result should be 1:

Shell
curl -sI https://example.com/ | grep -ci '^content-security-policy:'

Then test one URL under each path with its own policy, and scan the site with WebSec0. The headers report shows the policy it received and whether it passes.

Troubleshooting

Symptom Likely cause Fix
Two Content-Security-Policy headers The proxied application sends one too Add header_down -Content-Security-Policy inside reverse_proxy.
Per-path policy ignored The site-wide header line runs last and overwrites it Prefix the site-wide line with ?.
Application’s weak policy is sent instead of yours ? in front of reverse_proxy Drop the ? and add header_down -Content-Security-Policy.
File to import not found: security-headers The snippet is defined after the site block Move the snippet to the top of the Caddyfile.
Policy missing on 502 pages > in front of the field Drop the > and use header_down in the proxy.
Header missing, and caddy validate reports no error A double quote inside a double-quoted value splits it in two, which Caddy reads as a find-and-replace Wrap the value in backticks.
Inline scripts blocked after enforcing No nonce or hash for them Move them to files, or add hashes or application nonces.
Changes do not show up Reload skipped, or a CDN cached old headers caddy validate and reload, then purge the CDN.

Server hub

Every header on Caddy

Other web servers

Content-Security-Policy on other servers

Questions

Frequently asked questions

How do I add a Content-Security-Policy header in Caddy?

Add header Content-Security-Policy "default-src 'self'; …" inside the site block of your Caddyfile, then run caddy validate and reload Caddy.

Does Caddy send the CSP on error pages?

Yes. In our tests, the header was present on 404 responses from file_server, with and without a handle_errors block. There is no always flag to remember, unlike Nginx and Apache.

Why does my Caddy response have two Content-Security-Policy headers?

The application behind reverse_proxy sends one too, and Caddy keeps both. Add header_down -Content-Security-Policy inside reverse_proxy to drop the application's value. Avoid header >Content-Security-Policy: it replaces the value too, but Caddy's own 502 pages then have no policy.

Why is my per-path CSP ignored in Caddy?

Caddy sorts header directives by matcher: the most specific path runs first and the one without a matcher runs last, overwriting it. Prefix the site-wide line with ? so it only sets the header when no other line did.

How do I reuse the same CSP across several Caddy sites?

Define a snippet, such as (security-headers) { header { … } }, at the top of the Caddyfile and add import security-headers to each site block.

Can Caddy generate a CSP nonce?

Generate the nonce in your application, which writes it into both the HTML and the header, and keep Caddy from overwriting that header. For static sites, use hashes.

References

Sources

About the author

Portrait of Joshua Martinelle

Security engineer at Tenable

Security engineer at Tenable and web security researcher. He has disclosed more than 60 CVEs since 2020 and builds WebSec0.

Verify the change

Deployed it? Check it.

WebSec0 grades your TLS setup and security headers, including Content-Security-Policy, in a few seconds. Free, no account.

Scan your site