CORS Allow-Origin with Reverse Proxy

1. The problem I’m having:

I’m successfully making use of the reverse_proxy function to proxy incoming requests for particular folders to individual servers within my environment. Works well.

What I’m attempting to do now is to apply a CORS policy to a single one of these rulesets (example below). I’d like to prevent requests from domains outside of the defined scope of allowed origins.

The issue that I’m having is that I cannot seem to generate a valid Caddyfile. Obviously my method is wrong. I’ve had a poke through the help docs and tried a few examples from the forums, but cannot seem to get it to work. This is where I’d like some help.

2. Error messages and/or full log output:

[ec2-user@ip-x-x-x-x caddy]$ caddy reload
2023/03/19 22:05:44.940INFOusing adjacent Caddyfile
reload: adapting config using caddyfile: parsing caddyfile tokens for 'reverse_proxy': Caddyfile:8 - Error during parsing: unrecognized subdirective header

3. Caddy version:

caddy reload


caddy start

d. My complete Caddy config:

The Caddyfile in use


(cors) {
@origin{args.0} header Origin {args.0}
header @origin{args.0} Access-Control-Allow-Origin "{args.0}"
header @origin{args.0} Vary Origin
} {
reverse_proxy /nr*
reverse_proxy /appsm*
reverse_proxy /wxapi* {
    import cors
#Everything else is redirected here

Note: I’ve also tried using the following based on a forum post I found, though it seems to set the response header and not actually set a cors policy.

header_down Access-Control-Allow-Origin


header_up Access-Control-Allow-Origin

The header directive is a directive, it can’t be used as an option for another directive like reverse_proxy.

The reverse_proxy directive has header_up and header_down options. To write response headers, header_down can be used. The header_up option is for manipulating request headers being sent to your upstream app.

But ultimately, what you want is to use header, outside of reverse_proxy, to add response headers.

I recommend writing your config with handle blocks instead so you can do more than just one thing for each route. {
	handle /nr* {

	handle /wxapi* {
		import cors
		reverse_proxy /wxapi*

	# Everything else is handled here
	handle {

@francislavoie Thank you very much for the example. I’ll give this a go later in the week during a quiet period since changes will affect visible machines. I appreciate the explanation in your response, too.

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