天天看點

nginx location 的路由規則

~      #波浪線表示執行一個正則比對,區分大小寫

~*    #表示執行一個正則比對,不區分大小寫

^~    #^~表示普通字元比對,如果該選項比對,隻比對該選項,不比對别的選項,一般用來比對目錄

=      #進行普通字元精确比對

@     #"@" 定義一個命名的 location,使用在内部定向時,例如 error_page, try_files

location 比對的優先級(與location在配置檔案中的順序無關)

= 精确比對會第一個被處理。如果發現精确比對,nginx停止搜尋其他比對。

普通字元比對,正規表達式規則和長的塊規則将被優先和查詢比對,也就是說如果該項比對還需去看有沒有正規表達式比對和更長的比對。

^~ 則隻比對該規則,nginx停止搜尋其他比對,否則nginx會繼續處理其他location指令。

最後比對理帶有"~"和"~*"的指令,如果找到相應的比對,則nginx停止搜尋其他比對;當沒有正規表達式或者沒有正規表達式被比對的情況下,那麼比對程度最高的逐字比對指令會被使用。

location 優先級官方文檔

  1. Directives with the = prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops.
  3. Regular expressions, in order of definition in the configuration file.
  4. If #3 yielded a match, that result is used. Else the match from #2 is used.
  5. =字首的指令嚴格比對這個查詢。如果找到,停止搜尋。
  6. 所有剩下的正常字元串,最長的比對。如果這個比對使用^〜字首,搜尋停止。
  7. 正規表達式,在配置檔案中定義的順序。
  8. 如果第3條規則産生比對的話,結果被使用。否則,使用第2條規則的結果。
location  = / {
  # 隻比對"/".
  [ configuration A ] 
}
location  / {
  # 比對任何請求,因為所有請求都是以"/"開始
  # 但是更長字元比對或者正規表達式比對會優先比對
  [ configuration B ] 
}
location ^~ /images/ {
  # 比對任何以 /images/ 開始的請求,并停止比對 其它location
  [ configuration C ] 
}
location ~* .(gif|jpg|jpeg)$ {
  # 比對以 gif, jpg, or jpeg結尾的請求. 
  # 但是所有 /images/ 目錄的請求将由 [Configuration C]處理.   
  [ configuration D ] 
}      

二、 root和alias的差別

nginx指定檔案路徑有兩種方式root和alias,這兩者的用法差別,使用方法總結了下,友善大家在應用過程中,快速響應。root與alias主要差別在于nginx如何解釋location後面的uri,這會使兩者分别以不同的方式将請求映射到伺服器檔案上。

[root]

文法:root path

預設值:root html

配置段:http、server、location、if

[alias]

文法:alias path

配置段:location

root執行個體: 

location ^~ /t/ {
     root /www/root/html/;
}      

如果一個請求的URI是/t/a.html時,web伺服器将會傳回伺服器上的/www/root/html/t/a.html的檔案。

alias執行個體:

location ^~ /t/ {
 alias /www/root/html/new_t/;
}      

如果一個請求的URI是/t/a.html時,web伺服器将會傳回伺服器上的/www/root/html/new_t/a.html的檔案。注意這裡是new_t,因為alias會把location後面配置的路徑丢棄掉,把目前比對到的目錄指向到指定的目錄。

注意:

1. 使用alias時,目錄名後面一定要加"/"。

3. alias在使用正則比對時,必須捕捉要比對的内容并在指定的内容處使用。

4. alias隻能位于location塊中。(root可以不放在location中)

繼續閱讀