设置
当出现403跨域错误的时候 No 'Access-Control-Allow-Origin' header is present on the requested resource
,需要给Nginx
服务器配置响应的header
参数
- 在
Nginx
的配置文件中配置以下参数
location / {
add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
}
- 想要指定多个域名,
nginx
不支持这样写
add_header Access-Control-Allow-Origin http://client1.xxx.com,https://client2.xxx.com;
- 可以这么写
map $http_origin $corsHost {
default 0;
"~http://client1.xxx.com" http://client1.xxx.com;
"~http://client2.xxx.com" http://client2.xxx.com;
}
server {
# ...
location / {
add_header Access-Control-Allow-Origin $corsHost;
}
}
- 也可以设置白名单,这么写
server {
# ...
location / {
set $cors: '';
#$http_origin 获取http请求中header中的origin值
if ($http_origin ~* 'http://(localhost|127\.0\.0\.1).*') {
# 通过正则表达式设置白名单,通过白名单的则允许跨域
set $cors 'true';
}
if ($cors = 'true') {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
#为预检请求加的header
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
#为预检请求加的header
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,Keep-Alive,Origin,User-Agent,X-Requested-With';
}
#支持请求(带预检的跨域请求)的预检请求
if ( $request_method = 'OPTIONS') {
return 204;
}
}
}
备注
- 设置匹配所有的
Origin
且不带cookie
的
add_header Access-Control-Allow-Origin: *;
- 需要带
Cookie
,需设置
add_header Access-Control-Allow-Credentials:true;
- 匹配所有的
Origin
且带cookie
(千万不能同时设置Credentials=true
且Origin=*
,浏览器会报错)
#$http_origin 获取http请求中header中的origin值
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Origin $http_origin;
发表评论