服务器上创建⼀个⽂件 cors.conf ,建议放置在⽬录 /usr/local/nginx/conf/pugin:
# nginx 服务端配置跨域 add_header X-Frame-Options SAMEORIGIN; add_header X-Xss-Protection "1;mode=block"; add_header X-Content-Type-Options nosniff; add_header Strict-Transport-Security "max-age=15768000;includeSubdomains" always; # 注意其他需要配置到 location / 的内容都要放进来 location / { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; 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,User-Agent,X-Reques ted-With,If-Modified-Since,Cache-Control,Content-Type,Range'; # # 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-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Reques ted-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content -Range'; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Reques ted-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content -Range'; } } # 这个是针对服务器配置了pagespeed,如果没有,可以不配置下⾯的内容 location ~ "\.pagespeed\.(?:[a-z]\.)?[a-z]{2}\.[^.]{10}\.(css|js|jpg|jpeg| gif|png|webp)" { add_header 'Timing-Allow-Origin' "*"; add_header "Access-Control-Allow-Origin" "*"; add_header "Access-Control-Allow-Methods" "GET"; }
然后在主机配置中引入这个文件:
include /usr/local/nginx/conf/pugin/cors.conf;
最后记得要检测一下修改后的nginx配置文件是否正确。
以上内容参考自: https://enable-cors.org/server_nginx.html