nginx之location詳解


location有定位的意思,根據uri來進行不同的定位,在虛擬主機中是必不可少的,location可以定位網站的不同部分,定位到不同的處理方式上。

location匹配分類

精准匹配

精准匹配以=號為標志

location = /index.htm  {
    root /var/www/html/;
    index index.htm index.html;
}

location = /index.htm  {
    root html/;
    index index.htm index.html;
}
精准匹配的優先級要優於一般匹配,所以重啟nginx后會打開/var/www/html下面的index.htm而不會打開html下的index.htm

一般匹配

location / {
    root /usr/local/nginx/html;
    index index.htm index.html;
}

location /apis {
    root /var/www/html;
    index index.html;
}
我們訪問http://localhost/apis/
對於uri的/apis,兩個location的pattern都可以匹配它們
即‘/’能夠左前綴匹配,"/apis"也能夠左前綴匹配
但此時最終訪問的是目錄/var/www/html下的文件
因為apis/匹配的更長,因此使用該目錄下的文件

正則匹配

正則匹配以~符號為標志

location / {
    root /usr/local/nginx/html;
    index index.html index.htm;
}

location ~ image {
    root /var/www/;
    index index.html;
}

如果我們訪問,http://localhost/image/logo.png
此時"/"與 location /匹配成功
此時"image"正則與"image/logo.png"也匹配成功?誰發揮作用呢?
正則表達式的成果將會使用,會覆蓋前面的匹配
圖片會真正的返回/var/www/image/logo.png

總結

  • 1.先判斷精准命中,如果命中立即返回結果並結束解析過程
  • 2.判斷普通命中,如果有多個命中,記錄下來最長的命中結果,(記錄但不結束,最長的為准確)
  • 3.繼續判斷正則表達式的解析結果,按配置里的正則表達式順序為准,由上到下開始匹配,一旦匹配成功一個,立即返回結果,並結束解析過程。
  • 4.普通命中順序無所謂,按照命中的長短來確定
  • 5.正則命中有所謂,從前往后匹配命中


免責聲明!

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



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