Nginx和CORS问题

iyu*_*yur 6 javascript nginx xmlhttprequest cross-domain cors

我正在尝试在我的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';
 }
Run Code Online (Sandbox Code Playgroud)

似乎一切正常,但是当我尝试启动cors测试时,我收到XMLHttpRequest错误:

XMLHttpRequest无法加载http://xxxxxx.xxx/.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许来源" http://client.cors-api.appspot.com "访问.

似乎OPTIONS方法传递正常,但GET以错误结束.可能是什么?

nginx版本:nginx/1.4.6(Ubuntu)

Ole*_*leg 0

我假设您add_header在其中还有其他指令location。如果是这样,可能会出现意外行为。

看一下例子:

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";
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,仅Header 3会附加到响应中。这就是标准ngx_headers模块的工作原理。

您可以考虑使用ngx_headers_more模块重新编译 Nginx ,以便在使用标头时获得更多自由,或者不使用 Nginx 设置 CORS 标头,而是使用编写后端的编程语言。