使用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 后,就可以跨域了;這有些不符合常理,但是情況確實如此;
