轉載自:http://blog.chinaunix.net/uid-25196855-id-108805.htmlhtml
nginx 配置文件,自下到上分爲三種井井有條的結構:
| http block the protocol level
| server block the server level
V location block the requested URI
Nginx 容許用戶定義 Location block ,並指定一個匹配模式(pattern)匹配特定的 URI。除了簡單的字符串(好比文件系統路徑),還容許使用更爲複雜的匹配模式(pattern)。
Location block 的基本語法形式是:
location [=|~|~*|^~|@] pattern { ... }
[=|~|~*|^~|@] 被稱做 location modifier ,這會定義 Nginx 如何去匹配其後的 pattern ,以及該 pattern 的最基本的屬性(簡單字符串或正則表達式)。
------- 關於 location modifier -------
1. =
這會徹底匹配指定的 pattern ,且這裏的 pattern 被限制成簡單的字符串,也就是說這裏不能使用正則表達式。
Example:
server {
server_name website.com;
location = /abcd {
[…]
}
}
匹配狀況:
http://website.com/abcd # 正好徹底匹配
http://website.com/ABCD # 若是運行 Nginx server 的系統自己對大小寫不敏感,好比 Windows ,那麼也匹配
http://website.com/abcd?param1¶m2 # 忽略查詢串參數(query string arguments),這裏就是 /abcd 後面的 ?param1¶m2
http://website.com/abcd/ # 不匹配,由於末尾存在反斜槓(trailing slash),Nginx 不認爲這種狀況是徹底匹配
http://website.com/abcde # 不匹配,由於不是徹底匹配
2. (None)
能夠不寫 location modifier ,Nginx 仍然能去匹配 pattern 。這種狀況下,匹配那些以指定的 patern 開頭的 URI,注意這裏的 URI 只能是普通字符串,不能使用正則表達式。
Example:
server {
server_name website.com;
location /abcd {
[…]
}
}
匹配狀況:
http://website.com/abcd # 正好徹底匹配
http://website.com/ABCD # 若是運行 Nginx server 的系統自己對大小寫不敏感,好比 Windows ,那麼也匹配
http://website.com/abcd?param1¶m2 # 忽略查詢串參數(query string arguments),這裏就是 /abcd 後面的 ?param1¶m2
http://website.com/abcd/ # 末尾存在反斜槓(trailing slash)也屬於匹配範圍內
http://website.com/abcde # 仍然匹配,由於 URI 是以 pattern 開頭的
3. ~
這個 location modifier 對大小寫敏感,且 pattern 須是正則表達式
Example:
server {
server_name website.com;
location ~ ^/abcd$ {
[…]
}
}
匹配狀況:
http://website.com/abcd # 徹底匹配
http://website.com/ABCD # 不匹配,~ 對大小寫是敏感的
http://website.com/abcd?param1¶m2 # 忽略查詢串參數(query string arguments),這裏就是 /abcd 後面的 ?param1¶m2
http://website.com/abcd/ # 不匹配,由於末尾存在反斜槓(trailing slash),並不匹配正則表達式 ^/abcd$
http://website.com/abcde # 不匹配正則表達式 ^/abcd$
注意:對於一些對大小寫不敏感的系統,好比 Windows ,~ 和 ~* 都是不起做用的,這主要是操做系統的緣由。
4. ~*
與 ~ 相似,但這個 location modifier 不區分大小寫,pattern 須是正則表達式
Example:
server {
server_name website.com;
location ~* ^/abcd$ {
[…]
}
}
匹配狀況:
http://website.com/abcd # 徹底匹配
http://website.com/ABCD # 匹配,這就是它不區分大小寫的特性
http://website.com/abcd?param1¶m2 # 忽略查詢串參數(query string arguments),這裏就是 /abcd 後面的 ?param1¶m2
http://website.com/abcd/ # 不匹配,由於末尾存在反斜槓(trailing slash),並不匹配正則表達式 ^/abcd$
http://website.com/abcde # 不匹配正則表達式 ^/abcd$
5. ^~
匹配狀況相似 2. (None) 的狀況,以指定匹配模式開頭的 URI 被匹配,不一樣的是,一旦匹配成功,那麼 Nginx 就中止去尋找其餘的 Location 塊進行匹配了(與 Location 匹配順序有關)
6. @
用於定義一個 Location 塊,且該塊不能被外部 Client 所訪問,只能被 Nginx 內部配置指令所訪問,好比 try_files or error_page
------- 搜索順序以及生效優先級 -------
由於能夠定義多個 Location 塊,每一個 Location 塊能夠有各自的 pattern 。所以就須要明白(無論是 Nginx 仍是你),當 Nginx 收到一個請求時,它是如何去匹配 URI 並找到合適的 Location 的。
要注意的是,寫在配置文件中每一個 Server 塊中的 Location 塊的次序是不重要的,Nginx 會按 location modifier 的優先級來依次用 URI 去匹配 pattern ,順序以下:
1. =
2. (None) 若是 pattern 徹底匹配 URI(不是隻匹配 URI 的頭部)
3. ^~
4. ~ 或 ~*
5. (None) pattern 匹配 URI 的頭部
nginx