巧用Nginx配置解决跨域问题

打印 上一主题 下一主题

主题 915|帖子 915|积分 2745

页面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 : "<strong>http://www.xuecheng.com/api/auth/oauth/token</strong>",//发送请求的地址
复制代码
  1. function login(){        var uname = $("#username").val();        var pwd = $("#password").val();                 $.ajax({            url : "<strong>http://www.xuecheng.com/api/auth/oauth/token</strong>",//发送请求的地址             type: "post",            dataType: "json",            data : "username="+uname+"&password="+pwd+"&grant_type=password",            beforeSend:function (request) {                 // 如果后台没有跨域处理,这个自定义                 request.setRequestHeader("Authorization","Basic RG9jV2ViQXBwOjEyMzQ1Ng==");                 // 禁用按钮,防止重复提交                 $("#submit").attr({ disabled: "disabled" });            },            error : function() {                alert("error occured!!!");//请求失败时弹出的信息            },            success : function(data) {//返回的信息展示出来                alert(JSON.stringify(data))            }        });    };
复制代码
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.         }
  20.         
复制代码
其中的
$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;worker_processes  1;#error_log  logs/error.log;#error_log  logs/error.log  notice;#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {    worker_connections  1024;}http {    include       mime.types;    default_type  application/octet-stream;    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '    #                  '$status $body_bytes_sent "$http_referer" '    #                  '"$http_user_agent" "$http_x_forwarded_for"';    #access_log  logs/access.log  main;    sendfile        on;    #tcp_nopush     on;    #keepalive_timeout  0;    keepalive_timeout  65;    #gzip  on;        #微服务网关   [b] upstream apiserver{        server [/b][b]127.0.0.1:50101[/b][b];    }[/b]    server {        listen       80;      [b]  server_name  www.xuecheng.com;[/b]                ssi on;        ssi_silent_errors on;        #charset koi8-r;        #access_log  logs/host.access.log  main;               [b] #门户        location [/b][b]/ {            alias  D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/[/b][b];            index  index.html;        }[/b]        #location  / {        #   root /neworiental/www/jiaofu;        #   index index.html;        #   try_files $uri /index.html;        #}        # proxy_pass末尾有/,请求地址:http://localhost/api/test,转发地址:http://127.0.0.1:8000/test        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.         }
  20.                 location ^~ /openapi/auth/ {             proxy_pass http://apiserver/auth/;        }        #error_page  404              /404.html;        # redirect server error pages to the static page /50x.html        #        error_page   500 502 503 504  /50x.html;        location = /50x.html {            root   html;        }        # proxy the PHP scripts to Apache listening on 127.0.0.1:80        #        #location ~ \.php$ {        #    proxy_pass   http://127.0.0.1;        #}        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000        #        #location ~ \.php$ {        #    root           html;        #    fastcgi_pass   127.0.0.1:9000;        #    fastcgi_index  index.php;        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;        #    include        fastcgi_params;        #}        # deny access to .htaccess files, if Apache's document root        # concurs with nginx's one        #        #location ~ /\.ht {        #    deny  all;        #}    }    # another virtual host using mix of IP-, name-, and port-based configuration    #    #server {    #    listen       8000;    #    listen       somename:8080;    #    server_name  somename  alias  another.alias;    #    location / {    #        root   html;    #        index  index.html index.htm;    #    }    #}    # HTTPS server    #    #server {    #    listen       443 ssl;    #    server_name  localhost;    #    ssl_certificate      cert.pem;    #    ssl_certificate_key  cert.key;    #    ssl_session_cache    shared:SSL:1m;    #    ssl_session_timeout  5m;    #    ssl_ciphers  HIGH:!aNULL:!MD5;    #    ssl_prefer_server_ciphers  on;    #    location / {    #        root   html;    #        index  index.html index.htm;    #    }    #}}
复制代码
参考:
正确的Nginx跨域配置:https://blog.csdn.net/envon123/article/details/83270277
跨域资源共享(CORS)安全性:https://blog.csdn.net/weixin_43964148/article/details/109352413
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

半亩花草

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表