1、设置nginx允许所有域名跨域;
add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Origin $http_origin;
效果如下:
2、通过全局配置nginx白名单,仅能增加一个域名;
add_header 'Access-Control-Allow-Origin' 'https://www.baidu.com';
3、通过在路径下配置判断方法赋值,参考链接:
https://michielkalkman.com/snippets/nginx-cors-open-configuration/
#
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-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' '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' '*';
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' '*';
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';
}
}
server {
listen 8082;
server_name localhost;
location /test{
proxy_pass http://proxyedservice:8001/;
set $cors '';
if ( $http_origin ~* 'http://(localhost|127\.0\.0\.1).*') {
set $cors 'true';
}
if ($http_origin ~* "^https://www.baidu.com$") {
set $cors 'true';
}
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, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers'
'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
}
if ( $request_method = 'OPTIONS') {
return 204;
}
}
}
4、通过nginx的map实现跨域白名单配置;
map $http_origin $corsHost {
default 0;
"~https://www.itbiancheng.com" https://www.itbiancheng.com;
"~http://love.itbiancheng.com" http://love.itbiancheng.com;
}
server
{
listen 80;
server_name www.itbiancheng.com;
root /nginx;
location /
{
add_header Access-Control-Allow-Origin $corsHost;
}
}
来源:https://blog.csdn.net/u011067462/article/details/135451192
