经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Nginx » 查看文章
巧用Nginx配置解决跨域问题
来源:cnblogs  作者:我俩绝配  时间:2023/4/12 11:16:41  对本文有异议

页面nginx配置

1,前端页面放在域名根目录,比如,http://www.xuecheng.com/ ,对应的nginx配置:

  1. #门户
  2. location / {
  3. alias D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/;
  4. index index.html;
  5. }

页面目录:

接口nginx配置

2,前端请求接口路径,在域名后面加一个目录

  1. url : "http://www.xuecheng.com/api/auth/oauth/token",//发送请求的地址
  1. function login(){
  2. var uname = $("#username").val();
  3. var pwd = $("#password").val();
  4. $.ajax({
  5. url : "http://www.xuecheng.com/api/auth/oauth/token",//发送请求的地址
  6. type: "post",
  7. dataType: "json",
  8. data : "username="+uname+"&password="+pwd+"&grant_type=password",
  9. beforeSend:function (request) {
  10. // 如果后台没有跨域处理,这个自定义
  11. request.setRequestHeader("Authorization","Basic RG9jV2ViQXBwOjEyMzQ1Ng==");
  12. // 禁用按钮,防止重复提交
  13. $("#submit").attr({ disabled: "disabled" });
  14. },
  15. error : function() {
  16. alert("error occured!!!");//请求失败时弹出的信息
  17. },
  18. success : function(data) {//返回的信息展示出来
  19. alert(JSON.stringify(data))
  20. }
  21. });
  22. };

nginx 对api接口配置

  1. location /api/ {
  2. add_header 'Access-Control-Allow-Origin' $http_origin;
  3. add_header 'Access-Control-Allow-Credentials' 'true';
  4. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  5. add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
  6. add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
  7. if ($request_method = 'OPTIONS') {
  8. add_header 'Access-Control-Max-Age' 1728000;
  9. add_header 'Content-Type' 'text/plain; charset=utf-8';
  10. add_header 'Content-Length' 0;
  11. return 204;
  12. }
  13. proxy_pass http://apiserver/;
  14. proxy_set_header Host $host;
  15. proxy_set_header X-Real-IP $remote_addr;
  16. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  17. proxy_set_header X-Forwarded-Proto $scheme;
  18. proxy_connect_timeout 5;
  19. }

其中的

$http_origin

$http_origin并不是nginx的内置参数,nginx支持取自定义的参数值,$http_XXX这个格式是nginx取请求中header的XXX的值的。这里取的是origin,而一般跨域请求都会将请求的来源放在origin中(浏览器会往跨域请求的header上面加origin这个header)。

 

 

这样配置的话,前端页面在域名下:www.xuecheng.com,而访问的接口则是www.xuecheng.com/api/xxx ,这样就不存在跨域问题了,

其实nginx不配置  Access-Control-Allow-Origin也没事,因为前后端在一个域下了。

注意事项

如果你前后端访问存在跨域问题,而且你需要使用cookie,后端要想获取到前端携带过来的cookie,前后端都要做配置:

前端:

  1. var xhr = new XMLHttpRequest()
  2. xhr.withCredentials = true
  3. xhr.open('GET', 'http://localhost:8888/', true)
  4. xhr.send(null)

后端:

  1. Access-Control-Allow-Origin: http://www.abc.com(这里必须域名不能是*)
  2. Access-Control-Allow-Credentials: true

完整nginx配置

  1. #user nobody;
  2. worker_processes 1;
  3. #error_log logs/error.log;
  4. #error_log logs/error.log notice;
  5. #error_log logs/error.log info;
  6. #pid logs/nginx.pid;
  7. events {
  8. worker_connections 1024;
  9. }
  10. http {
  11. include mime.types;
  12. default_type application/octet-stream;
  13. #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  14. # '$status $body_bytes_sent "$http_referer" '
  15. # '"$http_user_agent" "$http_x_forwarded_for"';
  16. #access_log logs/access.log main;
  17. sendfile on;
  18. #tcp_nopush on;
  19. #keepalive_timeout 0;
  20. keepalive_timeout 65;
  21. #gzip on;
  22. #微服务网关
  23. upstream apiserver{
  24. server 127.0.0.1:50101;
  25. }
  26. server {
  27. listen 80;
  28. server_name www.xuecheng.com;
  29. ssi on;
  30. ssi_silent_errors on;
  31. #charset koi8-r;
  32. #access_log logs/host.access.log main;
  33. #门户
  34. location / {
  35. alias D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/;
  36. index index.html;
  37. }
  38. #location / {
  39. # root /neworiental/www/jiaofu;
  40. # index index.html;
  41. # try_files $uri /index.html;
  42. #}
  43. # proxy_pass末尾有/,请求地址:http://localhost/api/test,转发地址:http://127.0.0.1:8000/test
  44. location /api/ {
  45. add_header 'Access-Control-Allow-Origin' $http_origin;
  46. add_header 'Access-Control-Allow-Credentials' 'true';
  47. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  48. add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
  49. add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
  50. if ($request_method = 'OPTIONS') {
  51. add_header 'Access-Control-Max-Age' 1728000;
  52. add_header 'Content-Type' 'text/plain; charset=utf-8';
  53. add_header 'Content-Length' 0;
  54. return 204;
  55. }
  56. proxy_pass http://apiserver/;
  57. proxy_set_header Host $host;
  58. proxy_set_header X-Real-IP $remote_addr;
  59. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  60. proxy_set_header X-Forwarded-Proto $scheme;
  61. proxy_connect_timeout 5;
  62. }
  63. location ^~ /openapi/auth/ {
  64. proxy_pass http://apiserver/auth/;
  65. }
  66. #error_page 404 /404.html;
  67. # redirect server error pages to the static page /50x.html
  68. #
  69. error_page 500 502 503 504 /50x.html;
  70. location = /50x.html {
  71. root html;
  72. }
  73. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
  74. #
  75. #location ~ \.php$ {
  76. # proxy_pass http://127.0.0.1;
  77. #}
  78. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  79. #
  80. #location ~ \.php$ {
  81. # root html;
  82. # fastcgi_pass 127.0.0.1:9000;
  83. # fastcgi_index index.php;
  84. # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  85. # include fastcgi_params;
  86. #}
  87. # deny access to .htaccess files, if Apache's document root
  88. # concurs with nginx's one
  89. #
  90. #location ~ /\.ht {
  91. # deny all;
  92. #}
  93. }
  94. # another virtual host using mix of IP-, name-, and port-based configuration
  95. #
  96. #server {
  97. # listen 8000;
  98. # listen somename:8080;
  99. # server_name somename alias another.alias;
  100. # location / {
  101. # root html;
  102. # index index.html index.htm;
  103. # }
  104. #}
  105. # HTTPS server
  106. #
  107. #server {
  108. # listen 443 ssl;
  109. # server_name localhost;
  110. # ssl_certificate cert.pem;
  111. # ssl_certificate_key cert.key;
  112. # ssl_session_cache shared:SSL:1m;
  113. # ssl_session_timeout 5m;
  114. # ssl_ciphers HIGH:!aNULL:!MD5;
  115. # ssl_prefer_server_ciphers on;
  116. # location / {
  117. # root html;
  118. # index index.html index.htm;
  119. # }
  120. #}
  121. }

参考:

正确的Nginx跨域配置:https://blog.csdn.net/envon123/article/details/83270277

跨域资源共享(CORS)安全性:https://blog.csdn.net/weixin_43964148/article/details/109352413

 

原文链接:https://www.cnblogs.com/lihaoyang/p/17303937.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号