需求

关于跨域报错的坑 No 'Access-Control-Allow-Origin' header 这段时间折腾了很久究竟是在Java配置还是在Nginx配置,Nginx又要如何配置,最终结论是,个别国内浏览器是真的血坑,要么Chrome内核版本低的可怕,要么莫名其妙referer丢失。
总之是Nginx更适合用于防盗链和通配符跨域。
直接上配置

配置

直接上配置文件

  1. server {
  2. listen 443 ssl http2;
  3. server_name xxx.xxx.com;
  4. ...
  5. # 兼容旧浏览器内核
  6. ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4";
  7. location / {
  8. # referer防盗链开启 非本域名请求 返回403
  9. # 这里 none 和 blocked 是允许为空 用于兼容某些ZZ浏览器referer会丢失的情况
  10. valid_referers none blocked xxx.com *.xxx.com;
  11. if ($invalid_referer) {
  12. return 403;
  13. }
  14. # 跨域配置 其中options最好和其他方法分开 直接返回204
  15. # 这里允许的header需要逐一配置,个别ZZ浏览器会不兼容通配符,未配置的header会丢失
  16. # options请求不转给后端,直接返回204
  17. if ($request_method = OPTIONS) {
  18. add_header Access-Control-Allow-Origin $http_origin;
  19. add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
  20. add_header Access-Control-Allow-Credentials true;
  21. add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
  22. add_header Access-Control-Max-Age 1728000;
  23. return 204;
  24. }
  25. # 这里通过正则判断请求是否是来自xxx.com
  26. if ($http_origin ~ xxx\.com) {
  27. add_header Access-Control-Allow-Origin $http_origin;
  28. add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
  29. add_header Access-Control-Allow-Credentials true;
  30. add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
  31. add_header Access-Control-Max-Age 1728000;
  32. }
  33. ...
  34. }
  35. }