天天看點

NGINX location 在配置中的優先級

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

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

^~ 表示普通字元比對。使用字首比對。如果比對成功,則不再比對其他location。

= 進行普通字元精确比對。也就是完全比對。

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

NGINX location 在配置中的優先級

<a target="_blank"></a>

在nginx的location和配置中location的順序沒有太大關系。正location表達式的類型有關。相同類型的表達式,字元串長的會優先比對。

以下是按優先級排列說明:

等号類型(=)的優先級最高。一旦比對成功,則不再查找其他比對項。

^~類型表達式。一旦比對成功,則不再查找其他比對項。

正規表達式類型(~ ~*)的優先級次之。如果有多個location的正則能比對的話,則使用正規表達式最長的那個。

正常字元串比對類型。按字首比對。

配置項如下:

<code>location = / {</code>

<code># 僅僅比對請求 /</code>

<code>[ configuration a ]</code>

<code>}</code>

<code>location / {</code>

<code># 比對所有以 / 開頭的請求。</code>

<code># 但是如果有更長的同類型的表達式,則選擇更長的表達式。</code>

<code># 如果有正規表達式可以比對,則優先比對正規表達式。</code>

<code>[ configuration b ]</code>

<code>location /documents/ {</code>

<code># 比對所有以 /documents/ 開頭的請求。</code>

<code>[ configuration c ]</code>

<code>location ^~ /images/ {</code>

<code># 比對所有以 /images/ 開頭的表達式,如果比對成功,則停止比對查找。</code>

<code># 是以,即便有符合的正規表達式location,也不會被使用</code>

<code>[ configuration d ]</code>

<code>location ~* \.(gif|jpg|jpeg)$ {</code>

<code># 比對所有以 gif jpg jpeg結尾的請求。</code>

<code># 但是 以 /images/開頭的請求,将使用 configuration d</code>

<code>[ configuration e ]</code>

請求比對示例

<code>/ -&gt; configuration a</code>

<code>/index.html -&gt; configuration b</code>

<code>/documents/document.html -&gt; configuration c</code>

<code>/images/1.gif -&gt; configuration d</code>

<code>/documents/1.jpg -&gt; configuration e</code>

注意,以上的比對和在配置檔案中定義的順序無關。

<b>原文釋出時間為:2015-06-26</b>

<b></b>

<b>本文來自雲栖社群合作夥伴“linux中國”</b>

繼續閱讀