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

or

caddy start

d. My complete Caddy config:

The Caddyfile in use

{
email myemail@mymaindomain.com
debug
}

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

mymaindomain.com {
reverse_proxy /nr* 1.2.3.4:1880
reverse_proxy /appsm* 5.6.7.8:80
reverse_proxy /wxapi* 9.10.11.12:8000 {
    import cors https://theorigin.myotherdomain.com
}
#Everything else is redirected here
reverse_proxy 13.14.15.16:80
}

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 https://theorigin.myotherdomain.com

also

header_up Access-Control-Allow-Origin https://theorigin.myotherdomain.com

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.

example.com {
	handle /nr* {
		reverse_proxy 1.2.3.4:1880
	}

	handle /wxapi* {
		import cors
		reverse_proxy /wxapi* 9.10.11.12:8000
	}

	# Everything else is handled here
	handle {
		reverse_proxy 13.14.15.16:80
	}
}

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