Nginx 实现AJAX跨域请求

AJAX从一个域请求另一个域会有跨域的问题。那么如何在nginx上实现ajax跨域请求呢?要在nginx上启用跨域请求,需要添加add_header Access-Control*指令。如下所示:

location /{
add_header ‘Access-Control-Allow-Origin’ ‘http://other.subdomain.com’;
add_header ‘Access-Control-Allow-Credentials’ ‘true’;
add_header ‘Access-Control-Allow-Methods’ ‘GET’;

the rest of your configuration here

}

注释如下:

第一条指令:授权从other.subdomain.com的请求

第二条指令:当该标志为真时,响应于该请求是否可以被暴露

第三天指令:指定请求的方法,可以是GET,POST等

如果需要允许来自任何域的访问,可以这样配置:

Access-Control-Allow-Origin: *

ajax跨域请求测试

成功时,响应头是如下所示:
HTTP/1.1 200 OK
Server: nginx
Access-Control-Allow-Origin: other.subdomain.com

 


在Nginx location 里加上如下代码可以解决js 请求跨域问题

if ($request_method = ‘OPTIONS’) {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods ‘GET, POST, OPTIONS’;
add_header ‘Access-Control-Allow-Headers’ ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type’;
return 200;
}

if ($request_method = ‘POST’) {
add_header ‘Access-Control-Allow-Origin’ *;
add_header ‘Access-Control-Allow-Credentials’ ‘true’;
add_header ‘Access-Control-Allow-Methods’ ‘GET, POST, OPTIONS’;
add_header ‘Access-Control-Allow-Headers’ ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type’;
}

if ($request_method = ‘GET’) {
add_header ‘Access-Control-Allow-Origin’ *;
add_header ‘Access-Control-Allow-Credentials’ ‘true’;
add_header ‘Access-Control-Allow-Methods’ ‘GET, POST, OPTIONS’;
add_header ‘Access-Control-Allow-Headers’ ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type’;
}