使用Nginx來解決跨域的問題


使用Nginx來解決跨域的問題

nginx的版本:(查看nginx命令: /usr/local/nginx/sbin/nginx -v)
nginx/1.4.3

問題是:前端項目域名是 a.xxxx.com, 后端的接口域名是 b.xxx.com,然后后端接口沒有設置跨域相關的響應設置頭,因此就接口和我們
域名就會存在跨域的情況,因此我們可以使用 nginx服務器來配置一下;

網上很多資料將 在nginx配置下 加如下代碼就可以解決跨域的問題;

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET,POST;

比如在nginx上如下配置:

server {
    listen 443;
    listen 80;
    server_name b.xxx.com;
    access_log  /data/www/logs/nginx/access.log main;

    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Credentials true;
    add_header Access-Control-Allow-Methods GET,POST;

    include nginx_xxx.conf;
    location / {
        proxy_pass http://192.168.1.212:8136;
        #proxy_pass http://xd-mfa-mng/;
        include nginx_proxy.conf;
    }
    error_page   500 502 503 504  /502.html;
    location = /50x.html {
        oot   html;
    }
}

但是還是會存在跨域的情況,俗話說,夢想是美好的,但是現實很殘酷的。因此我們需要指定 對應的域名就可以解決上面的跨域問題了

add_header Access-Control-Allow-Origin http://a.xxx.com; 

如上配置就可以使用nginx解決跨域的問題了;

因此代碼變為如下:

server {
    listen 443;
    listen 80;
    server_name b.xxx.com;
    access_log  /data/www/logs/nginx/access.log main;

    add_header Access-Control-Allow-Origin http://a.xxx.com; 
    add_header Access-Control-Allow-Credentials true;

    include nginx_xxx.conf;
    location / {
        proxy_pass http://192.168.1.212:8136;
        #proxy_pass http://xd-mfa-mng/;
        include nginx_proxy.conf;
    }
    error_page   500 502 503 504  /502.html;
    location = /50x.html {
        oot   html;
    }
}

注意:

1. Access-Control-Allow-Origin
服務器默認是不允許跨域的,給Nginx服務器配置 Access-Control-Allow-Origin *; 后的含義,表示服務器可以接受所有的請求源,即接受所有跨域的請求。但是這樣設置在項目中並沒有解決跨域,但是設置了具體的項目域名,比如 http://a.xxx.com 后,就可以跨域了;這有些不符合常理,但是情況確實如此;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM