1

In the .htaccess file on my web server, I have the following CORS header set:

Header set Access-Control-Allow-Origin "example.com"

In one of my PHP scripts, that I frequently call while working from localhost, I have this header set:

header("Access-Control-Allow-Origin: *");

This has worked for me up until yesterday, when I turned on FPM for PHP. Now I get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.com/script.php. (Reason: CORS header 'Access-Control-Allow-Origin' does not match '*, example.com').

I'm only getting that error when calling from localhost, not while calling from the website. I'm wondering if there's a way to override the .htaccess CORS header via PHP now that FPM is enabled.

MrWhite
  • 12,647
  • 4
  • 29
  • 41

1 Answers1

0

Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘*, example.com’

Curious, that's as if Header merge had been called, rather than Header set? "Merged" values like this are not officially supported by the Allow-Control-Allow-Origin header, so browser support may vary and will explain why it's not working for you.

if there's a way to override the .htaccess CORS header via PHP now that FPM is enabled.

I think you'll need to try and make it so that Apache doesn't override the header set by PHP (which is set earlier), rather than PHP override Apache. Try the setifempty action:

Header setifempty Access-Control-Allow-Origin "example.com"

You can also try the always condition, ie. Header always set .... - this is a different "group" of headers to the default onsuccess and should mean that the header is effectively set twice.

However, I don't believe that multiple Access-Control-Allow-Origin headers is strictly part of the standard either, so browser's could vary in their behaviour.

See also the following related question on StackOverflow:

MrWhite
  • 12,647
  • 4
  • 29
  • 41
  • Apache sets headers after php? Interesting. Well, setifempty is giving the same error. – XtevensChannel Jan 12 '21 at 01:32
  • Ordinarily, yes. (Although it does seem odd that your headers appeared to work OK before? You would have needed `setifempty` before IMO?!) The order seems to be indicated in the error response: `'*, example.com'` - but it also seems odd that the header appears to be _merged_, not overwritten (as mentioned above)? You can also try the `always` condition, ie. `Header always set ....` - this is a different "group" of headers and should mean that the header is effectively set twice. You should debug this my examining the HTTP response headers in the browser (and add these to your question). – MrWhite Jan 12 '21 at 03:45
  • Also, do you _need_ to set this header in PHP? You could set the header conditionally in `.htaccess` based on the URL (or file) being requested. – MrWhite Jan 12 '21 at 04:02
  • 1
    Adding `always` fixed it perfectly! Thanks – XtevensChannel Jan 12 '21 at 09:18