We are facing an issue with Pages. If an incoming request matches multiple rules’ URL patterns, it’s inheriting all rules’ headers even if they are the same header instead of overriding the header of the less specific pattern.
We are trying to set Content Security Policy headers for our website via the
_headers file. But we are facing an issue. We need to set a unique CSP header for every page. And to specify the CSP header for 404 pages, we are specifying the header under
/* to match all the URLs.
But the problem is, Cloudflare is sending both the headers for the current and 404 routes. The headers for more specific URL patterns, such as
/blog, etc. are not overriding the header for
And no matter where we put the header for the
/* route, top or bottom, Cloudflare is always sending it before the header of the current route.
As a result, the header for the 404 page is being applied to all the pages. And it’s breaking the functionality of all our pages except the 404 pages .
Any help on this issue would be much appreciated. Thanks in advance!
From pages documentation:
An incoming request which matches multiple rules’ URL patterns will inherit all rules’ headers.
Thank you for your response, @Cyb3r-Jak3. It’s the correct behavior when the headers are different because then you won’t have to write the same header again and again. But the problem is when the headers are the same. It’s definitely an issue if the same header is not being overridden but rather being inherited.
What is the order of the headers file?
Some headers are valid when there are multiple of them (such as Set-Cookie): I expect that’s why this is the behavior of Pages.
The order of the
_headers file is:
But the order doesn’t matter in this case. Because like I said above, I have tried putting the rules for
/* at the end of the file. But Cloudflare always sends those rules before others.
Perhaps, but it’s not the case for
content-security-policy. And I haven’t tested it personally, but from a Netlify forum post, I got to know that Netlify overrides the rules for less specific URL patterns. If it’s not possible for Cloudflare to figure out what headers should be overridden and what should not be, there should still be a way for us to avoid this. I couldn’t find any way to avoid this situation. There’s not something like a negate pattern to match all the URls but not match a list of URLs.
BTW, hi @mcfadyeni! Hope you are doing well. Nice to see you in the Cloudflare community.
We were unable to resolve this issue. But we managed to find a solution. The solution was to use the
_headers file to set the unique header for each page and then create a response headers modification rule via the Cloudflare Rulesets API that matches all URLs except the routes for the available pages.