代理傳遞上的 nginx CORS:跨來源請求被封鎖:同源策略不允許讀取遠端資源

代理傳遞上的 nginx CORS:跨來源請求被封鎖:同源策略不允許讀取遠端資源

我將 API 從一個子網域移到另一個子網域,而不影響已經執行的應用程式。我在 nginx 上配置了三台伺服器,例如:

原始API伺服器:

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;
 }
...
}

代理透過伺服器:

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;
}
...
}

AJAX 呼叫曾經在舊 api 上完美運行,但是對於新 api,我在 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 '*, *').

在 Safari 上:

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

新舊 api 上的冰壺顯示:

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

我該如何解決這個問題?

答案1

解決方案是不要為代理傳遞伺服器的 CORS 新增 add_header,因為這會重複標頭或使用 set_header

代理透過伺服器:

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;
}
...
}

相關內容