網上看了很多nginx的location配置,寫的感覺我看的都不是很明白。記錄下自己的使用經驗。
語法規則: location [=|~|~*|^~] /uri/ { … }
示例:
location /user/ { proxy_pass http://user.example.com; }
= ~這些我們稱為location修飾符,他們定義了匹配模式
/user/ 這些我們稱之為 匹配路徑
## location修飾符
這個容易看的眼花繚亂,一個個捋清楚。
= 等於號即要求請求的地址和匹配路徑完全相同
~ 波浪號表示匹配路徑是正則表達式,加上*變成~*后表示大小寫敏感
^~ 在~前面加上^就表示如果匹配到了就不匹配正則表達式的路徑
## 重點規則
然后我們再確定一個原則,nginx做的是最長匹配,再規則中優先匹配長的。比如地址是 /user/api 會被匹配到/user/api的location而不會匹配到/user/的規則。
其次,先檢查普通 匹配路徑再檢測 正則路徑。
Let’s illustrate the above by an example:
location = / { [ configuration A ] } location / { [ configuration B ] } location /documents/ { [ configuration C ] } location ^~ /images/ { [ configuration D ] } location ~* \.(gif|jpg|jpeg)$ { [ configuration E ] }
The “/
” request will match configuration A, the “/index.html
” request will match configuration B, the “/documents/document.html
” request will match configuration C, the “/images/1.gif
” request will match configuration D, and the “/documents/1.jpg
” request will match configuration E.
如果是proxy_pass配置到iis的應用程序,在proxy_pass里最好不寫路徑只寫網站級別
a.com/app 轉發到原始的 192.168.1.2/app
這兩個后綴必須一樣,否則會轉發失敗。