tyxiayu 发表于 2016-12-26 08:49:56

nginx中配置跨域支持功能

  在nginx.conf中配置
http {
  ......
  add_header Access-Control-Allow-Origin *;
  add_header Access-Control-Allow-Headers X-Requested-With;
  add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
  ......
}  这样就可以实现GET,POST,OPTIONS的跨域请求的支持
也可以 add_header Access-Control-Allow-Origin http://test.51testing.com; --指定允许的url;

配置项详细解释:w3c-Cross-Origin Resource Sharing
在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';
页: [1]
查看完整版本: nginx中配置跨域支持功能