我正在将 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 上的 Curling 显示:
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;
}
...
}