a2005147 发表于 2016-12-25 09:06:10

在Nginx上配置CORS

Cross-Origin Resource Sharing (CORS)是W3C出的一个标准,是用来解决JavaScript跨域调用的问题。以下是在Nginx上面配置CORS。

location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '$http_origin';
#
# Om nom nom cookies
#
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' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
#
# 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_origin';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
}
}


在如上的配置当中,'Access-Control-Allow-Origin'用了'$http_origin',这样是适用于开发环境,这样多台开发测试设备都可以跨域请求。当上了生产环境,出于安全考虑,最好设置一个白名单来限制访问的设备。
页: [1]
查看完整版本: 在Nginx上配置CORS