Nginx CORS on proxy pass: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

corsnginxPROXY

I am moving my APIs from a subdomain to another without affecting already running applications. I have three servers configured on nginx such as:

Original API server:

server {
listen       80;
server_name  example.com;

root  /var/www/example/;

index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$args;

add_header 'Access-Control-Allow-Origin' '*';

location / {
   try_files $uri $uri/ /index.php?$args;
}

 location ~*/api/([a-zA-Z0-9_]+) {
    proxy_pass      http://127.0.0.1:4343/api/$1;
    proxy_read_timeout 60s;

    proxy_set_header          Host            $host;
    proxy_set_header          X-Real-IP       $remote_addr;
    proxy_set_header          X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header 'Access-Control-Allow-Origin' '*';
    proxy_set_header 'Access-Control-Allow-Credentials' true;
 }
...
}

Proxy passed server:

server {
listen 4343;
server_name _;

root  /var/www/exampleapi/;

index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$args;

add_header 'Access-Control-Allow-Origin' '*';

location / {
   try_files $uri $uri/ /index.php?$args;
}
...
}

The AJAX call used to work perfectly on the old apis, however for the new ones I am getting an error on FF:

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

And on Safari:

XMLHttpRequest cannot load https://example.com/api/startup. Origin https://myclient.com is not allowed by Access-Control-Allow-Origin.

Curling on both new and old apis shows:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *

How may I solve this issue?

Best Answer

The solution to this was not to add add_header for CORS for the Proxy Passed server as this duplicates the header or to use set_header

Proxy passed server:

server {
listen 4343;
server_name _;

root  /var/www/exampleapi/;

index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$args;

location / {
   try_files $uri $uri/ /index.php?$args;
}
...
}