1. 程式人生 > 其它 >nginx根據路徑配置反向代理

nginx根據路徑配置反向代理

  今天,測試 一個後臺介面,寫了個html,在其中使用jquery傳送請求給後臺,chrome91竟然報錯說跨域給error了!那豈不是以後本機頁面不能和後端愉快的玩耍了?

  於是,配置起了nginx+反向代理的方式,旨在迂迴對抗chrome的新安全機制。

目標地址:http://127.0.0.1:8006/publish/template/modifyInterPublish

配置如下:

 1 server {
 2     listen       80;
 3     server_name  localhost;
 4 
 5     location / {
 6         root   html;
7 index index.html index.htm; 8 if ($request_filename ~* ^.*?\.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx|jar|war)$) { 9 add_header Content-Disposition 'attachment'; 10 } 11 } 12 13 location /proxy { 14 proxy_pass http://127.0.0.1:8006; 15 index index.html;
16 } 17 18 }

結果:怎麼也訪問不到!

原來只差一個“/”!

即:

1 location /proxy {
2     proxy_pass http://127.0.0.1:8006;
3     index index.html;
4 }

改為:

1 location /proxy {
2     proxy_pass http://127.0.0.1:8006/;
3     index index.html;
4 }

原來proxy_pass匹配路徑後加槓代理後將去掉已匹配的路徑,不加槓則保留已匹配的路徑。

請求網址:http://127.0.0.1:8006/publish/template/modifyInterPublish

使用proxy_pass http://127.0.0.1:8006;代理後的網址為:http://127.0.0.1:8006/proxy/publish/template/modifyInterPublish

使用proxy_pass http://127.0.0.1:8006/;代理後的網址為:http://127.0.0.1:8006/publish/template/modifyInterPublish

而location匹配的路徑後有沒有槓無所謂,即

location /proxylocation /proxy/ 匹配的結果沒有區別。

最後再上正確的配置:

 1 server {
 2     listen       80;
 3     server_name  localhost;
 4 
 5     location / {
 6         root   html;
 7         index  index.html index.htm;
 8         if ($request_filename ~* ^.*?\.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx|jar|war)$) {
 9             add_header Content-Disposition 'attachment'; 
10         }
11     }
12 
13     location /proxy {
14         proxy_pass http://127.0.0.1:8006/;
15         index index.html;
16     }
17     
18 }