nginx在反向代理的時候,proxy_pass需要指定路徑,
有無"/"
的區別,如下:
location /lile { 配置一: proxy_pass http://192.168.0.37/; 配置二: proxy_pass http://192.168.0.37; }
環境說明:
反向代理服務器:192.168.0.224
真實數據機器:192.168.0.37
1:先配置真實數據機的nginx配置文件
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; root /web1 location /lile { root /data; index index.html; } } }
創建對應的文件夾:
mkdir /web1 echo "My location is /web1" > index.html mkdir -p /data/lile echo "My location is /data/lile" > index.html
2:反向代理的配置文件為
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log logs/access.log main; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location /lile { 配置一:proxy_pass http://192.168.0.37; 配置二:proxy_pass http://192.168.0.37/ } } }
3:測試
當proxy_pass為:
http://192.168.0.37
的時候,返回的數據如下:
1)瀏覽器請求訪問http://192.168.0.224/lile/
2)到達192.168.0.224后,location /lile 匹配到之后,轉發的地址為:
http://192.168.0.37/lile/
3)然后到達192.168.0.37,匹配到了location /lile,所以就去/data目錄下取數據

當proxy_pass為: http://192.168.0.37/ 的時候,返回的數據如下:
1)瀏覽器請求訪問http://192.168.0.224/lile/
2)達192.168.0.224后,location /lile 匹配到之后,轉發的地址為:http://192.168.0.37/,這里在proxy_pass的 http://192.168.0.37/ 的“/”會把/lile給替換掉
3)然后到達192.168.0.37,直接匹配到的是root /web1,所以就去/web1目錄下取數據

4:其他
在上面的location若為/,沒有其他的具體匹配值,那么這兩個的訪問無區別
location / { 配置一: proxy_pass http://192.168.0.37/; 配置二: proxy_pass http://192.168.0.37; }
配置一轉發的時候,新的URI替換原有的得到的還是 http://192.168.0.37/
配置二轉發的時候,不會發生改變 http://192.168.0.37/
5:總結
proxy_pass URL(http://192.168.0.224/uri/)
當URL中含有URI時,Nginx服務器會使用新的URI替換原有的URI(這里的新的URI理解為proxy_pass URL里的URI)
當URL中不含URI時,Nginx服務器不會改變原有地址的URI
這里的URI與URL暫且不去討論它是怎么定義的,就理解為域名或者IP地址之后的路徑(暫時還沒弄清楚他們兩個的區別)
注:學習《nginx高性能Web服務器詳解》的時候總結