Caddy v2 CORS settings

1. The problem I’m having:

Hello. Where I can find actually documentation about CORS settings for Caddy v2?

2. Error messages and/or full log output:

PASTE OVER THIS, BETWEEN THE ``` LINES.
Please use the preview pane to ensure it looks nice.

3. Caddy version:

v2.6.4

4. How I installed and ran Caddy:

a. System environment:

docker

b. Command:

docker run -ti caddy:v2.6.4 caddy run --config /etc/caddy/Caddyfile

c. Service/unit/compose file:

PASTE OVER THIS, BETWEEN THE ``` LINES.
Please use the preview pane to ensure it looks nice.

d. My complete Caddy config:

PASTE OVER THIS, BETWEEN THE ``` LINES.
Please use the preview pane to ensure it looks nice.

5. Links to relevant resources:

Use the header directive to set the response headers you need.

The specifics of CORS are out of scope of Caddy itself, you can read about the individual CORS headers on the MDN docs:

Do you have some best practice change header

Access-Control-Allow-Origin

Based on Host header? Article Setup CORS in Caddy 2 not actual for v2.64

You could do something like this:

(cors) {
	@origin header Origin {args.0}
	header @origin {
		Access-Control-Allow-Origin "{args.0}"
		Access-Control-Request-Method GET
	}
}

origin1.com {
	import cors origin1.com
}

origin2.com {
	import cors origin2.com
}
1 Like

How can I use IF for this block?

if ({http_origin} == "https://example.com") {
  import cors https://example.com
}
if ({http_origin} == "https://example123.org") {
  import cors https://example123.org
}

No. That’s not how Caddy works, there’s no if.

See the docs, you need to use request matchers and apply those to handlers.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.