记录:nginx 配置 CORS 跨域共享相关
# 可以设置通配符*,允许被所有域使用
add_header 'Access-Control-Allow-Origin' '*';
# 允许客户端携带验证信息,例如 cookie 之类的
add_header 'Access-Control-Allow-Credentials' 'true';
# 是在响应预检请求的时候使用,用来指明在实际的请求中,可以使用哪些自定义 HTTP 请求头
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken';
# 表示允许的跨域请求的方法,在当前请求的域被允许后,还要检查当前请求的方法是否被允许
add_header 'Access-Control-Allow-Methods' 'GET,POST, OPTIONS';
# 响应报头指示哪些报头可以公开为通过列出他们的名字的响应的一部分
add_header 'Access-Control-Expose-Headers' 'X-Auth-Token';
# 表示预请求的结果的有效期是多久,单位为秒
add_header 'Access-Control-Max-Age' 1728000;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' "3600" ;
add_header 'Access-Control-Allow-Origin' 'http://pm.example.com';
add_header 'Access-Control-Allow-Headers' 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,X-Auth-Token';
add_header 'Access-Control-Expose-Headers' 'X-Auth-Token';
return 200;
}
重启Nginx
/usr/local/openresty/nginx/sbin/nginx -s reload
测试跨域请求
# 测试POST请求(成功)
curl -I -X POST -H "Origin: http://example.com" https://www.aaa.top/
# 测试OPTIONS请求(成功)
curl -I -X OPTIONS -H "Origin: http://example.com" https://www.aaa.top/
# 测试PUT请求(不成功)
curl -I -X PUT -H "Origin: http://example.com" https://www.aaa.top/
成功时,响应头是如下所示:
不成功时,响应头如下所示:
# 判断请求的域
set $cors '';
if ( $http_origin ~ (http://www.example1.com|(.*).example1.com|http://(.*).example1.com) ){
set $cors 'true';
}
# 用于判断请求Methods: OPTIONS
set $isoption 1;
if ($cors = 'true') {
set $isoption "${isoption}1";
}
if ($cors = 'true') {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' "GET,POST,OPTIONS";
add_header 'Access-Control-Allow-Headers' "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since";
add_header 'Access-Control-Expose-Headers' "X-Requested-With";
add_header 'Access-Control-Max-Age' "600";
}
# 判断请求Methods: OPTIONS
if ($request_method = 'OPTIONS') {
set $isoption "${isoption}1";
}
if ($isoption = '111') {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' "GET,POST,OPTIONS";
add_header 'Access-Control-Allow-Headers' "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since";
add_header 'Access-Control-Expose-Headers' "X-Requested-With";
add_header 'Access-Control-Max-Age' "600";
return 200;
}