1. 程式人生 > 實用技巧 >Nginx中location模組的詳細配置

Nginx中location模組的詳細配置

Nginx中location模組的詳細配置(含示例)

題記

此前在配置Nginx location模組的時候玩出了一些bug,折騰了一段時間。後來網上也查閱了相關的資料,看著也比較混亂。週末有空想著好好整理一下location模組的配置,結合自己的親手實驗,總結了location模組的配置。

location模組配置

根據匹配特性大概可以分成以下幾個部分(按優先順序順序)

最高優先順序(=) 第二優先順序(^~) 第三優先順序(按照順序匹配,*) 第四優先順序(/)

1. 匹配即停止

=:表示精確匹配,要麼就匹配上,要麼就不會被匹配。如果匹配上了,就進入該location塊,其他都不看。

~:表示優先匹配,如果按從上往下的順序匹配到了該~後面的URL,那麼就進入該location塊,其他都不看。

2. 按順序匹配

~:表示區分大小寫的正則匹配,如果依照自上而下的順序匹配上URL了,那就不會再繼續尋找,即使用這個location塊。
~*:表示不區分大小寫的正則匹配,如果依照自上而下的順序匹配上URL了,那就不會再繼續尋找,即使用這個location塊。

3. 通用匹配

/:表示任何請求都會被匹配到。

location使用舉例

# 輸入http://ip+port/images/1.p
# 此時顯示的是'= /images/1.p',因為=匹配優先順序最高
location = /images/1.p {
    default_type 'text/plain';
    echo '= /images/1.p';
}
location ^~ /images/1.p {
    default_type 'text/plain';
    echo ' /images/1.p';
}
# 輸入http://ip+port/images/1.p
# 此時顯示到的是'^~ /images/1.p',因為^~只要匹配到了就會停止匹配,哪怕後續的長度更長
location ^~ /images/ {
    default_type 'text/plain';
    echo '^~ /images/1.p';
}
location ~ /images/1.p {
    default_type 'text/plain';
    echo '~ /images/1.p';
}
# 輸入http://ip+port/images/1.pxyzxyz
# 此時顯示到的是'~ /images/',因為這是按照順序匹配的,匹配到了後面的就不再匹配了
location ~ /images/ {
    default_type 'text/plain';
    echo '~ /images/';
}
location ~ /images/1 {
    default_type 'text/plain';
    echo '~ /images/1';
}
# 輸入http://ip+port/images/  顯示'/',因為沒有匹配到後面的URL,使用預設的/規則
# 輸入http://ip+port/images/1xyzxyz  顯示'~ /images/1',因為匹配到了後面的正則
location / {
    default_type 'text/plain';
    echo '/';
}
location ~ /images/1 {
    default_type 'text/plain';
    echo '~ /images/1';
}
# 輸入http://ip+port/images/ 顯示'/images/'
# 輸入http://ip+port/images/1/ab 顯示'/images/'
# 輸入http://ip+port/images/1/abc 顯示'/images/1/abc'  匹配上第一個location後,會繼續向下匹配尋找,如果有更加完整的匹配,則會有下面的。如果沒有,則使用當前的。
location /images/ {
    default_type 'text/plain';
    echo '/images/';
}
location /images/1/abc {
    default_type 'text/plain';
    echo '/images/1/abc';
}

注意事項

# 在使用“=”的時候會有意外情況,比方說下面這個例子。當輸入'http://ip+port/'時,發現返回的狀態碼是304&404
# 原因在於Nginx發現請求的是個目錄時,會重定向去請求'http://ip+port/index.html',此時返回碼是304
# 而後Nginx收到了'http://ip+port/index.html'這個請求,發現沒有location能夠匹配,就返回404了
location = / {
    default_type 'text/plain';
    index index.html index.htm;
    root /web/;
}