我正在尝试在我的 nginx 服务器上设置 cors。
我已经把它放到我的虚拟主机设置到位置部分:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'http://client.cors-api.appspot.com';
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' 'http://client.cors-api.appspot.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' 'http://client.cors-api.appspot.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
似乎一切正常,但是当我尝试启动 cors 测试时,出现 XMLHttpRequest 错误:
XMLHttpRequest cannot load http://xxxxxx.xxx/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://client.cors-api.appspot.com' is therefore not allowed access.
似乎,OPTIONS 方法通过正常,但 GET 以错误结束。它可能是什么?
nginx 版本:nginx/1.4.6 (Ubuntu)
请您参考如下方法:
我假设您在该位置
中还有其他add_header
指令。如果是这样,可能会出现意外行为。
看例子:
location /somelocation {
add_header "Header 1" "Value 1";
set $a 1;
if ($a = 1) {
add_header "Header 2" "Value 2";
}
set $b 2;
if ($b = 2) {
add_header "Header 3" "Value 3";
}
return 200 "Some response\n";
}
在这种情况下,只有 Header 3
将附加到响应中。这就是标准 ngx_headers
模块的工作方式。
你可以考虑用 ngx_headers_more
module 重新编译 Nginx在使用 header 时获得更多自由,或者设置 CORS header 而不是使用 Nginx,而是使用编写后端的编程语言。