nginx location介紹
Nginx 中的 Location 指令 是NginxHttpCoreModule中重要指令。Location 指令,是用來為匹配的 URI 進行配置,URI 即語法中的”/uri/”,可以是字符串或正則表達式。但如果要使用正則表達式,則必須指定前綴。
nginx location語法
基本語法:location [=|~|~*|^~] /uri/ { … }
= 嚴格匹配。如果這個查詢匹配,那么將停止搜索并立即處理此請求。
~ 為區分大小寫匹配(可用正則表達式)
~* 為不區分大小寫匹配(可用正則表達式)
!~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配
^~ 如果把這個前綴用于一個常規字符串,那么告訴nginx 如果路徑匹配那么不測試正則表達式。
nginx location應用實例
location = / { # 只匹配 / 查詢。 }
location / { # 匹配任何查詢,因為所有請求都已 / 開頭。但是正則表達式規則和長的塊規則將被優先和查詢匹配。 }
location ^~ /images/ { # 匹配任何已 /images/ 開頭的任何查詢并且停止搜索。任何正則表達式將不會被測試。 }
location ~* /.(gif|jpg|jpeg)$ { # 匹配任何已 gif、jpg 或 jpeg 結尾的請求。 }
location ~* /.(gif|jpg|swf)$ { valid_referers none blocked start.igrow.cn sta.igrow.cn; if ($invalid_referer) { #防盜鏈 rewrite ^/ http://$host/logo.png; }}
location ~* /.(js|css|jpg|jpeg|gif|png|swf)$ {if (-f $request_filename) { #根據文件類型設置過期時間 expires 1h; break;}}
location ~* /.(txt|doc)${ #禁止訪問某個目錄 root /data/www/wwwroot/linuxtone/test; deny all;}
以下是補充:
Nginx Location基本語法
location
syntax: location [=|~|~*|^~] /uri/ { … }
語法:location [=|~|~*|^~] /uri/ { … }
default: no
默認:否
context: server
上下文:server
This directive allows different configurations depending on the URI. It can be configured using both conventional strings and regular expressions. To use regular expressions, you must use the prefix ~* for case insensitive match and ~ for case sensitive match.
這個指令隨URL不同而接受不同的結構。你可以配置使用常規字符串和正則表達式。如果使用正則表達式,你必須使用 ~* 前綴選擇不區分大小寫的匹配或者 ~ 選擇區分大小寫的匹配。
To determine which location directive matches a particular query, the conventional strings are checked first. Conventional strings match the beginning portion of the query and are case-sensitive - the most specific match will be used (see below on how nginx determines this). Afterwards, regular expressions are checked in the order defined in the configuration file. The first regular expression to match the query will stop the search. If no regular expression matches are found, the result from the convention string search is used.
新聞熱點
疑難解答