nginx反向代理配置里的location 反斜杠用法


兩台nginx服務器

nginx A: 192.168.1.48

nginx B: 192.168.1.56

一. 測試方法

在nginx A中配置不同的規則,然后請求nginx A: http://192.168.1.48/foo/api

觀察nginx B收到的請求,具體操作是查看:'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

二. 測試過程及結果

案例1

nginx A配置:

 

location /foo/ {
  proxy_pass http://192.168.1.56/; } 

 

nginx B收到的請求:/api

案例2

nginx A配置:

 

location /foo {
  proxy_pass http://192.168.1.56/; } 

 

nginx B收到的請求://api

案例3

nginx A配置:

 

location /foo {
  proxy_pass http://192.168.1.56; } 

 

nginx B收到的請求:/foo/api

案例4

nginx A配置:

 

location /foo/ {
  proxy_pass http://192.168.1.56; } 

 

 

nginx B收到的請求:/foo/api

案例5

nginx A配置:

 

location /foo/ {
  proxy_pass http://192.168.1.56/bar/; } 

 

nginx B收到的請求:/bar/api

案例6

nginx A配置:

 

location /foo {
  proxy_pass http://192.168.1.56/bar/; } 

 

nginx B收到的請求:/bar//api

案例7

nginx A配置:

 

location /foo/ {
  proxy_pass http://192.168.1.56/bar; } 

 

nginx B收到的請求:/barapi

案例8

nginx A配置:

 

location /foo {
  proxy_pass http://192.168.1.56/bar; } 

 

nginx B收到的請求:/bar/api

看到這里是不是都暈了呢,其實是有規律的

現在把這些案例按表格排列起來,結果表示nginx B收到的請求

表一

 
案例 location proxy_pass 結果
1 /foo/ http://192.168.1.48/ /api
2 /foo http://192.168.1.48/ //api
3 /foo/ http://192.168.1.48 /foo/api
4 /foo http://192.168.1.48 /foo/api

 

 

 

 

 

 

 

表二

 
案例 location proxy_pass 結果
5 /foo/ http://192.168.1.48/bar/ /bar/api
6 /foo http://192.168.1.48/bar/ /bar//api
7 /foo/ http://192.168.1.48/bar /barapi
8 /foo http://192.168.1.48/bar /bar/api

 

 

 

 

 

 

 

. 解析

原請求路徑:本文中統一為 "/foo/api"

location: 上面表格中的location列

proxy_pass:上面表格中的proxy_pass列

新請求路徑:nginx將原請求路徑處理過后的字符串

重點對 proxy_pass 進行分析,可以分為3種形式

然后按照ip:port后是否接了字符串歸為2類,"/"也是字符串,因此1歸為一類,2、3歸為一類,下面對這兩類情況進行說明

當 proxy_pass 的 ip:port 后未接字符串的時候,nginx 會將原請求路徑原封不動地轉交給下一站 nginx,如案例3和4

當 proxy_pass 的 ip:port 后接了字符串的時候,nginx 會將 location 從 原請求路徑 中剔除,再將剩余的字符串拼接到 proxy_pass 后生成 新請求路徑,然后將 新請求路徑 轉交給下一站nginx(上面一種情況實際上和這個是一樣的,只不過剔除的字符串是空串~~)

舉個最讓人疑惑的例子:案例7。proxy_pass 的 ip:port 后接了字符串 "/bar",因此將 location:"/foo/" 從 原請求路徑:"/foo/api" 中剔除,變為"api",再將"api"拼接到proxy_pass: http://192.168.1.48/bar 后生成了新請求url:" http://192.168.1.48/barapi ",因此下一站的nginx收到的請求就是 "/barapi"。

案例6:proxy_pass 的 ip:port 后接了字符串 "/bar/",因此將 location:"/foo" 從 原請求路徑 "/foo/api" 中剔除,變為 "/api",再將 "/api" 拼接到proxy_pass: http://192.168.1.48/bar/ 后生成了 新請求路徑:" http://192.168.1.48/bar//api ",因此下一站的nginx收到的請求就是 /bar//api。

其它的案例都可以以此類推,現在終於搞明白了,再也不用一頭霧水。

轉載 https://www.jb51.net/article/146975.htm,僅供自己學習


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM