CORS Headers are altered in the browser resulting in content becoming blocked CORS Headers are altered in the browser resulting in content becoming blocked nginx nginx

CORS Headers are altered in the browser resulting in content becoming blocked


The issue could be similar as my answer here:

The server is not configured to respond to OPTIONS requests with the correct "Access-Control-Allow-" headers.

Opening the url in a new Tab is a GET request and is working because it is not making a preflight request, as it meets the criteria to be a simple request as defined by the CORS documentation

On the other hand, the ajax request is a POST request and meets the criteria to be a Preflighted request, meaning a preflight OPTIONS request should be made first.

In short, you have correctly setup the CORS response headers, but the server is not configured to add these headers for OPTIONS method requests.

The solution is to handle OPTIONS requests on the server code with a 2xx response and add the **Access-Control-Allow- as you do for GET and POST requests. Keep in mind that OPTIONS requests do not include any parameters, so this should be done before any validation or request parsing.

Moreover, according to Access-Control-Allow-Origin documentation:

If the server specifies a single origin rather than the "*" wildcard, then the server should also include Origin in the Vary response header — to indicate to clients that server responses will differ based on the value of the Origin request header.

So set the Vary response header also:

eg at the top of you script try:

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");    header("Access-Control-Allow-Credentials: true");    header("Vary: Origin");    exit;}

References

Preflighted requests

response for preflight 403 forbidden


The problem is that you use header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); (BTW: not very recommended) and you get the wrong header. I bet on one of the reasons:

  • The web server overwrites the headers.
  • The browser uses cache, although it should not. (BFC).
  • You did not upload the updated code to the requesting server.

Let's start from the end.

  • Do not believe herself, verify. (Not once did I look, we do not work, and then came the reflection that I did not upload changes :) ).
  • Turn off the cache in the browser debugger. (you must have open debugger) If this is a problem and the function is to be available in the pool, add timestamp to the request.
  • Check the configuration of nginx / apache / server panel

Are you aware that the construction used by you is synonymous with Access-Control-Allow-Origin: *? You should check HTTP_ORIGIN if it belongs to the allowed pool.