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/;
}


免責聲明!

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



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