• 巧用Nginx配置解决跨域问题


    页面nginx配置

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

    复制代码
    #门户
            location / {
                alias  D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/;
                index  index.html;
            }
    复制代码

    页面目录:

    接口nginx配置

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

    url : "http://www.xuecheng.com/api/auth/oauth/token",//发送请求的地址 
    复制代码
    function login(){
            var uname = $("#username").val();
            var pwd = $("#password").val();
            
             $.ajax({
                url : "http://www.xuecheng.com/api/auth/oauth/token",//发送请求的地址 
                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接口配置

    复制代码
    location /api/ {
                add_header 'Access-Control-Allow-Origin' $http_origin;
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                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';
                add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
                if ($request_method = 'OPTIONS') {
                    add_header 'Access-Control-Max-Age' 1728000;
                    add_header 'Content-Type' 'text/plain; charset=utf-8';
                    add_header 'Content-Length' 0;
                    return 204;
                }
               proxy_pass http://apiserver/; 
               proxy_set_header Host $host;
               proxy_set_header X-Real-IP $remote_addr;
               proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
               proxy_set_header X-Forwarded-Proto $scheme;
               proxy_connect_timeout 5;
            }
            
    复制代码

    其中的

    $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,前后端都要做配置:

    前端:

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

    后端:

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

    完整nginx配置

    复制代码
    #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;
        
        #微服务网关
        upstream apiserver{
            server 127.0.0.1:50101;
        }
    
        server {
            listen       80;
            server_name  www.xuecheng.com;
            
            ssi on;
            ssi_silent_errors on;
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
            
            #门户
            location / {
                alias  D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/;
                index  index.html;
            }
            #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/ {
                add_header 'Access-Control-Allow-Origin' $http_origin;
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                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';
                add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
                if ($request_method = 'OPTIONS') {
                    add_header 'Access-Control-Max-Age' 1728000;
                    add_header 'Content-Type' 'text/plain; charset=utf-8';
                    add_header 'Content-Length' 0;
                    return 204;
                }
               proxy_pass http://apiserver/; 
               proxy_set_header Host $host;
               proxy_set_header X-Real-IP $remote_addr;
               proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
               proxy_set_header X-Forwarded-Proto $scheme;
               proxy_connect_timeout 5;
            }
            
            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

     

  • 相关阅读:
    算法竞赛进阶指南 基本算法 0x07 贪心
    Flask(Jinja2) 服务端模板注入漏洞(SSTI)
    openfoam 智能指针探索
    连花清瘟卖断货?近一个月解热药价格暴涨33%,销额超206万元
    使用Arthas诊断线上问题的常见命令(热更新,监听耗时,方法出入参,jvm信息)
    (一)gitblit安装教程
    CUDA高性能计算经典问题②:前缀和
    MySQL数据库进阶第五篇(锁)
    缓存一致性解决方案——改数据时如何保证缓存和数据库中数据的一致性
    socket转modbus协议转换应用案例介绍
  • 原文地址:https://www.cnblogs.com/lihaoyang/p/17303937.html