1. 程式人生 > >Nginx之Location配置詳解(Location匹配順序)

Nginx之Location配置詳解(Location匹配順序)

location有”定位”的意思, 主要是根據Uri來進行不同的定位.在虛擬主機的配置中,是必不可少的.

location可以把網站的不同部分,定位到不同的處理方式上.

1.location的基礎語法

location [=|~|~*|^~] patt {

}

=:嚴格匹配。如果這個查詢匹配,那麼將停止搜尋並立即處理此請求。
~:為區分大小寫匹配(可用正則表示式)。
~*:為不區分大小寫匹配(可用正則表示式)。
^~:如果把這個字首用於一個常規字串,那麼告訴nginx 如果路徑匹配那麼不測試正則表示式。

2.location如何發揮作用
location匹配過程

3.簡單例項證明上述圖片結論

不帶正則表示式的匹配過程

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

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

location配置如上,若訪問http://xxx.com/,定位的流程是:
1:精準匹配命中"/",得到index頁為index.htm,所以請求的地址變為http://xxx.com/index.htm
2:再次匹配"/index.htm",此次內部轉跳uri已經是"/index.htm",命中普通匹配"/"
,根目錄為/usr/local/nginx/html 3:最終結果,訪問了/usr/local/nginx/html/index.htm

帶正則表示式的匹配過程

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

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

如果我們訪問http://xx.com/image/logo.png。此時uri為"/image/logo.png"命中了普通匹配"/",也命中了正則匹配"~ image",但是根據上述圖片中匹配過程分析,最終是正則匹配生效。

所以最終訪問地址為:/var/www
/image/logo.png。如果你想最終的匹配路徑為/var/www/logo.png可以把正則匹配中的"root /var/www/";修改為"alias /var/www/"