1. 程式人生 > >nginx用反向代理機制解決跨域的問題

nginx用反向代理機制解決跨域的問題

nginx nginx跨域 nginx反向代理 甘兵

什麽是跨域?

使用js獲取數據時,涉及到的兩個url只要協議、域名、端口有任何一個不同,都被當作是不同的域,相互訪問就會有跨域問題。

跨域,指的是瀏覽器不能執行其他網站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器施加的安全限制。

所謂同源是指,域名,協議,端口均相同,不明白沒關系,舉個栗子:

http://www.123.com/index.html 調用 http://www.123.com/server.php (非跨域)

http://www.123.com/index.html 調用 http://www.456.com/server.php (主域名不同:123/456,跨域)

http://abc.123.com/index.html 調用 http://def.123.com/server.php (子域名不同:abc/def,跨域)

http://www.123.com:8080/index.html 調用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)

http://www.123.com/index.html 調用 https://www.123.com/server.php (協議不同:http/https,跨域)

請註意:localhost和127.0.0.1雖然都指向本機,但也屬於跨域。

瀏覽器執行javascript腳本時,會檢查這個腳本屬於哪個頁面,如果不是同源頁面,就不會被執行。

背景

大家看了上面的跨域介紹,相信都大致了解所謂的跨域訪問。正好我們公司這兩天就有這種需求,公司前端工程師提出需要跨域訪問,需求如下:

nginx服務器:172.18.18.75

h5服務器:172.18.18.76

java服務器:172.18.18.77

新增加域名:www.oilup.com 指向 nginx服務器(172.18.18.75)

域名指向的靜態目錄:/usr/local/nginx/html/web/ 目錄放在nginx服務器(172.18.18.75)

[root@localhost web]# pwd

/usr/local/nginx/html/web

[root@localhost web]# ls

css handlebars images init.html package.json README.md

gulpfile.js html index.html js pc.zip template


當訪問域名http://www.oilup.com/ 調用 http://172.18.18.76:7080

當訪問域名http://www.oilup.com/ 調用 http://172.18.18.77:8888

如何解決

進入nginx服務器,配置nginx.conf:

#vim /usr/local/nginx/conf/nginx.conf

http {

include mime.types;

default_type application/octet-stream;

sendfile on;

#增加下面3行

add_header Access-Control-Allow-Origin *;

add_header Access-Control-Allow-Headers X-Requested-With;

add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

......

其它http項的配置省略


#配置server,用location匹配並反向代理proxy_pass

server {

listen 80;

server_name www.oilup.com;

location / {

root html/web;

index index.html index.htm;

}

location /h5/ {

rewrite ^.+h5/?(.*)$ /$1 break;

include uwsgi_params;

proxy_pass http://172.18.18.76:7080;

}

location /javaes/ {

rewrite ^.+javaes/?(.*)$ /$1 break;

include uwsgi_params;

proxy_pass http://172.18.18.77:8888;

}

}


重啟nginx服務:

/usr/local/nginx/sbin/nginx -s reload


測試訪問

技術分享圖片


nginx用反向代理機制解決跨域的問題