Modifying a response header using Transform Rules

Hi all,

I want to modify the response header using transform rules so that CORs would allow certain domains and block others.

If I create a rule like this:

If hostname equals sub.domain.com
Set static access-control-allow-origin = *

This works.

But I don’t want to use a wildcard but rather instead only allow sub1.domain.com and sub2.domain.com. However, my problem is that if I use sub1.domain.com instead of * it doesn’t work. It seems that my “syntax” is incorrect. How can I add two subdomains to the “access-control-allow-origin”.

Thanks!

Are you saying you cannot set a response header like this? It works fine on my zone.

1 Like

Hi Albert,

I never tried with just one domain as I need two.

I can say that:
Set static Acces-Control-Allow-Origin sub1.domain.com, sub2.domain.com doesn’t work.
Maybe the issue is the comma?

That works fine for me. Could you please send a screenshot of the entire rule and the error you are seeing?


image

1 Like

So the issue I have is not directly related to Cloudflare I guess as the header value is indeed set correctly. by Cloudflare.

The error in console I get is this:
The ‘Access-Control-Allow-Origin’ header contains multiple values ‘sub1.domain.com, sub2.domain.com’, but only one is allowed.

I guess this is outside of scope of support of Cloudflare community.

Thanks!

This can be achieved with Cloudflare. You can use Transform Rules to dynamically set the Access-Control-Allow-Origin header to the domain that sent the CORS request.

If (http.host eq "cors-target.example.com" and http.request.headers["origin"][0] in {"https://allowed-origin-1.example.com" "https://allowed-origin-2.example.com"}) then set dynamic Access-Control-Allow-Origin to http.request.headers["origin"][0].

$ curl -i -H 'Origin: https://allowed-origin-1.example.com' https://cors-target.example.com/
Access-Control-Allow-Origin: https://allowed-origin-1.example.com

$ curl -i -H 'Origin: https://allowed-origin-2.example.com' https://cors-target.example.com/
Access-Control-Allow-Origin: https://allowed-origin-2.example.com

$ curl -i -H 'Origin: https://disallowed-origin.example.com' https://cors-target.example.com/
Access-Control-Allow-Origin: NOT PRESENT
2 Likes

Thanks a lot! Super helpful!

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