巧用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配置解决跨域问题_第1张图片

接口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)。

巧用NGINX配置解决跨域问题_第2张图片

这样配置的话,前端页面在域名下: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,运维)