1. 程式人生 > >proxy_pass根據path路徑轉發時的"/"問題記錄

proxy_pass根據path路徑轉發時的"/"問題記錄

記錄 server write color listen roo upstream 匹配 stream

在nginx中配置proxy_pass時,如果是按照^~匹配路徑時,要註意proxy_pass後的url最後的/。當加上了/,相當於是絕對根路徑,則nginx不會把location中匹配的路徑部分代理走;如果沒有/,則會把匹配的路徑部分也給代理走。

比如下面設置:
location ^~ /wangshibo/ 
{ 
proxy_cache js_cache; 
proxy_set_header Host js.test.com; 
proxy_pass http://js.test.com/; 
}
如上面的配置,如果請求的url是http://servername/wangshibo/test.html會被代理成http://js.test.com/test.html

而如果這麽配置
location ^~ /wangshibo/ 
{ 
proxy_cache js_cache; 
proxy_set_header Host js.test.com; 
proxy_pass http://js.test.com; 
}
則請求的url是http://servername/wangshibo/test.html會被代理到http://js.test.com/wangshibo/test.html

當然,可以用如下的rewrite來實現/的功能
location ^~ /wangshibo/ 
{ 
proxy_cache js_cache; 
proxy_set_header Host js.test.com; 
rewrite /wangshibo/(.+)$ /$1 break; 
proxy_pass http://js.test.com; 
} 

-----------------------------------------------------看看下面的實例--------------------------------------------------------------

1)第一種配置
[[email protected]_16_202_V vhosts]# cat ssl-wangshibo.conf
upstream at {
    server 172.29.16.202:8080 max_fails=3 fail_timeout=30s;
}
 
server {
   listen 443;
   server_name www.wangshibo.com;
   ssl on;
 
   ### SSL log files ###
   access_log logs/wangshibo_access.log;
   error_log logs/wangshibo_error.log;
 
### SSL cert files ###
   ssl_certificate ssl/bkjk.cer;     
   ssl_certificate_key ssl/bkjk.key;  
 
   location /attendance/ {
   proxy_pass http://at;                                                          //不需要加上"/"                      
   proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
   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 https;
   proxy_redirect off;
       }
 
}
 
訪問https://www.wangshibo.com/attendance/和http://172.29.16.202:8080/attendance結果是一致的。
 
2)第二種配置
[[email protected]
/* */_16_202_V vhosts]# cat ssl-wangshibo.conf upstream at { server 172.29.16.202:8080 max_fails=3 fail_timeout=30s; } server { listen 443; server_name www.wangshibo.com; ssl on; ### SSL log files ### access_log logs/wangshibo_access.log; error_log logs/wangshibo_error.log; ### SSL cert files ### ssl_certificate ssl/bkjk.cer; ssl_certificate_key ssl/bkjk.key; location / { proxy_pass http://at/attendance/; //一定要加上"/" proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; 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 https; proxy_redirect off; } } 訪問https://www.wangshibo.com和http://172.29.16.202:8080/attendance結果是一致的。

proxy_pass根據path路徑轉發時的"/"問題記錄