Nginx跨域设置

设置

当出现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=trueOrigin=*,浏览器会报错)
#$http_origin 获取http请求中header中的origin值 add_header Access-Control-Allow-Credentials true; add_header Access-Control-Allow-Origin $http_origin;

创作不易,若本文对你有帮助,欢迎打赏支持作者!

 分享给好友: