nginx規則總結


  1 location正則寫法
  2 一個示例:
  3 
  4 location  = / {
  5   # 精確匹配 / ,主機名后面不能帶任何字符串
  6   [ configuration A ] 
  7 }
  8 
  9 location  / {
 10   # 因為所有的地址都以 / 開頭,所以這條規則將匹配到所有請求
 11   # 但是正則和最長字符串會優先匹配
 12   [ configuration B ] 
 13 }
 14 
 15 location /documents/ {
 16   # 匹配任何以 /documents/ 開頭的地址,匹配符合以后,還要繼續往下搜索
 17   # 只有后面的正則表達式沒有匹配到時,這一條才會采用這一條
 18   [ configuration C ] 
 19 }
 20 
 21 location ~ /documents/Abc {
 22   # 匹配任何以 /documents/ 開頭的地址,匹配符合以后,還要繼續往下搜索
 23   # 只有后面的正則表達式沒有匹配到時,這一條才會采用這一條
 24   [ configuration CC ] 
 25 }
 26 
 27 location ^~ /images/ {
 28   # 匹配任何以 /images/ 開頭的地址,匹配符合以后,停止往下搜索正則,采用這一條。
 29   [ configuration D ] 
 30 }
 31 
 32 location ~* \.(gif|jpg|jpeg)$ {
 33   # 匹配所有以 gif,jpg或jpeg 結尾的請求
 34   # 然而,所有請求 /images/ 下的圖片會被 config D 處理,因為 ^~ 到達不了這一條正則
 35   [ configuration E ] 
 36 }
 37 
 38 location /images/ {
 39   # 字符匹配到 /images/,繼續往下,會發現 ^~ 存在
 40   [ configuration F ] 
 41 }
 42 
 43 location /images/abc {
 44   # 最長字符匹配到 /images/abc,繼續往下,會發現 ^~ 存在
 45   # F與G的放置順序是沒有關系的
 46   [ configuration G ] 
 47 }
 48 
 49 location ~ /images/abc/ {
 50   # 只有去掉 config D 才有效:先最長匹配 config G 開頭的地址,繼續往下搜索,匹配到這一條正則,采用
 51     [ configuration H ] 
 52 }
 53 
 54 location ~* /js/.*/\.js
 55 已=開頭表示精確匹配
 56 如 A 中只匹配根目錄結尾的請求,后面不能帶任何字符串。
 57 ^~ 開頭表示uri以某個常規字符串開頭,不是正則匹配
 58 ~ 開頭表示區分大小寫的正則匹配;
 59 ~* 開頭表示不區分大小寫的正則匹配
 60 / 通用匹配, 如果沒有其它匹配,任何請求都會匹配到
 61 順序 no優先級: (location =) > (location 完整路徑) > (location ^~ 路徑) > (location ~,~* 正則順序) > (location 部分起始路徑) > (/)
 62 
 63 上面的匹配結果 按照上面的location寫法,以下的匹配示例成立:
 64 
 65 / -> config A
 66 精確完全匹配,即使/index.html也匹配不了
 67 /downloads/download.html -> config B
 68 匹配B以后,往下沒有任何匹配,采用B
 69 /images/1.gif -> configuration D
 70 匹配到F,往下匹配到D,停止往下
 71 /images/abc/def -> config D
 72 最長匹配到G,往下匹配D,停止往下
 73 你可以看到 任何以/images/開頭的都會匹配到D並停止,FG寫在這里是沒有任何意義的,H是永遠輪不到的,這里只是為了說明匹配順序
 74 /documents/document.html -> config C
 75 匹配到C,往下沒有任何匹配,采用C
 76 /documents/1.jpg -> configuration E
 77 匹配到C,往下正則匹配到E
 78 /documents/Abc.jpg -> config CC
 79 最長匹配到C,往下正則順序匹配到CC,不會往下到E
 80 實際使用建議
 81 所以實際使用中,個人覺得至少有三個匹配規則定義,如下:
 82 #直接匹配網站根,通過域名訪問網站首頁比較頻繁,使用這個會加速處理,官網如是說。
 83 #這里是直接轉發給后端應用服務器了,也可以是一個靜態首頁
 84 # 第一個必選規則
 85 location = / {
 86     proxy_pass http://tomcat:8080/index
 87 }
 88 # 第二個必選規則是處理靜態文件請求,這是nginx作為http服務器的強項
 89 # 有兩種配置模式,目錄匹配或后綴匹配,任選其一或搭配使用
 90 location ^~ /static/ {
 91     root /webroot/static/;
 92 }
 93 location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
 94     root /webroot/res/;
 95 }
 96 #第三個規則就是通用規則,用來轉發動態請求到后端應用服務器
 97 #非靜態文件請求就默認是動態請求,自己根據實際把握
 98 #畢竟目前的一些框架的流行,帶.php,.jsp后綴的情況很少了
 99 location / {
100     proxy_pass http://tomcat:8080/
101 }
102 http://tengine.taobao.org/book/chapter_02.html
103 http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
104 
105 Rewrite規則
106 rewrite功能就是,使用nginx提供的全局變量或自己設置的變量,結合正則表達式和標志位實現url重寫以及重定向。rewrite只能放在server{},location{},if{}中,並且只能對域名后邊的除去傳遞的參數外的字符串起作用,例如 http://seanlook.com/a/we/index.php?id=1&u=str 只對/a/we/index.php重寫。語法rewrite regex replacement [flag];
107 
108 如果相對域名或參數字符串起作用,可以使用全局變量匹配,也可以使用proxy_pass反向代理。
109 
110 表明看rewrite和location功能有點像,都能實現跳轉,主要區別在於rewrite是在同一域名內更改獲取資源的路徑,而location是對一類路徑做控制訪問或反向代理,可以proxy_pass到其他機器。很多情況下rewrite也會寫在location里,它們的執行順序是:
111 
112 執行server塊的rewrite指令
113 執行location匹配
114 執行選定的location中的rewrite指令
115 如果其中某步URI被重寫,則重新循環執行1-3,直到找到真實存在的文件;循環超過10次,則返回500 Internal Server Error錯誤。
116 
117 flag標志位
118 last : 相當於Apache的[L]標記,表示完成rewrite
119 break : 停止執行當前虛擬主機的后續rewrite指令集
120 redirect : 返回302臨時重定向,地址欄會顯示跳轉后的地址
121 permanent : 返回301永久重定向,地址欄會顯示跳轉后的地址
122 因為301和302不能簡單的只返回狀態碼,還必須有重定向的URL,這就是return指令無法返回301,302的原因了。這里 last 和 break 區別有點難以理解:
123 
124 last一般寫在server和if中,而break一般使用在location中
125 last不終止重寫后的url匹配,即新的url會再從server走一遍匹配流程,而break終止重寫后的匹配
126 break和last都能組織繼續執行后面的rewrite指令
127 if指令與全局變量
128 if判斷指令
129 語法為if(condition){...},對給定的條件condition進行判斷。如果為真,大括號內的rewrite指令將被執行,if條件(conditon)可以是如下任何內容:
130 
131 當表達式只是一個變量時,如果值為空或任何以0開頭的字符串都會當做false
132 直接比較變量和內容時,使用=或!=
133 ~正則表達式匹配,~*不區分大小寫的匹配,!~區分大小寫的不匹配
134 -f和!-f用來判斷是否存在文件
135 -d和!-d用來判斷是否存在目錄
136 -e和!-e用來判斷是否存在文件或目錄
137 -x和!-x用來判斷文件是否可執行
138 
139 例如:
140 
141 if ($http_user_agent ~ MSIE) {
142     rewrite ^(.*)$ /msie/$1 break;
143 } //如果UA包含"MSIE",rewrite請求到/msid/目錄下
144 
145 if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
146     set $id $1;
147  } //如果cookie匹配正則,設置變量$id等於正則引用部分
148 
149 if ($request_method = POST) {
150     return 405;
151 } //如果提交方法為POST,則返回狀態405(Method not allowed)。return不能返回301,302
152 
153 if ($slow) {
154     limit_rate 10k;
155 } //限速,$slow可以通過 set 指令設置
156 
157 if (!-f $request_filename){
158     break;
159     proxy_pass  http://127.0.0.1; 
160 } //如果請求的文件名不存在,則反向代理到localhost 。這里的break也是停止rewrite檢查
161 
162 if ($args ~ post=140){
163     rewrite ^ http://example.com/ permanent;
164 } //如果query string中包含"post=140",永久重定向到example.com
165 
166 location ~* \.(gif|jpg|png|swf|flv)$ {
167     valid_referers none blocked www.jefflei.com www.leizhenfang.com;
168     if ($invalid_referer) {
169         return 404;
170     } //防盜鏈
171 }
172 全局變量
173 下面是可以用作if判斷的全局變量
174 
175 $args : #這個變量等於請求行中的參數,同$query_string
176 $content_length : 請求頭中的Content-length字段。
177 $content_type : 請求頭中的Content-Type字段。
178 $document_root : 當前請求在root指令中指定的值。
179 $host : 請求主機頭字段,否則為服務器名稱。
180 $http_user_agent : 客戶端agent信息
181 $http_cookie : 客戶端cookie信息
182 $limit_rate : 這個變量可以限制連接速率。
183 $request_method : 客戶端請求的動作,通常為GET或POST。
184 $remote_addr : 客戶端的IP地址。
185 $remote_port : 客戶端的端口。
186 $remote_user : 已經經過Auth Basic Module驗證的用戶名。
187 $request_filename : 當前請求的文件路徑,由root或alias指令與URI請求生成。
188 $scheme : HTTP方法(如http,https)。
189 $server_protocol : 請求使用的協議,通常是HTTP/1.0或HTTP/1.1190 $server_addr : 服務器地址,在完成一次系統調用后可以確定這個值。
191 $server_name : 服務器名稱。
192 $server_port : 請求到達服務器的端口號。
193 $request_uri : 包含請求參數的原始URI,不包含主機名,如:”/foo/bar.php?arg=baz”。
194 $uri : 不帶請求參數的當前URI,$uri不包含主機名,如”/foo/bar.html”。
195 $document_uri : 與$uri相同。
196 例:http://localhost:88/test1/test2/test.php
197 $host:localhost
198 $server_port:88
199 $request_uri:http://localhost:88/test1/test2/test.php
200 $document_uri:/test1/test2/test.php
201 $document_root:/var/www/html
202 $request_filename:/var/www/html/test1/test2/test.php
203 
204 常用正則
205 . : 匹配除換行符以外的任意字符
206 ? : 重復0次或1次
207 + : 重復1次或更多次
208 * : 重復0次或更多次
209 \d :匹配數字
210 ^ : 匹配字符串的開始
211 $ : 匹配字符串的介紹
212 {n} : 重復n次
213 {n,} : 重復n次或更多次
214 [c] : 匹配單個字符c
215 [a-z] : 匹配a-z小寫字母的任意一個
216 小括號()之間匹配的內容,可以在后面通過$1來引用,$2表示的是前面第二個()里的內容。正則里面容易讓人困惑的是\轉義特殊字符。
217 
218 rewrite實例
219 例1:
220 
221 http {
222     # 定義image日志格式
223     log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;
224     # 開啟重寫日志
225     rewrite_log on;
226 
227     server {
228         root /home/www;
229 
230         location / {
231                 # 重寫規則信息
232                 error_log logs/rewrite.log notice; 
233                 # 注意這里要用‘’單引號引起來,避免{}
234                 rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4;
235                 # 注意不能在上面這條規則后面加上“last”參數,否則下面的set指令不會執行
236                 set $image_file $3;
237                 set $image_type $4;
238         }
239 
240         location /data {
241                 # 指定針對圖片的日志格式,來分析圖片類型和大小
242                 access_log logs/images.log mian;
243                 root /data/images;
244                 # 應用前面定義的變量。判斷首先文件在不在,不在再判斷目錄在不在,如果還不在就跳轉到最后一個url里
245                 try_files /$arg_file /image404.html;
246         }
247         location = /image404.html {
248                 # 圖片不存在返回特定的信息
249                 return 404 "image not found\n";
250         }
251 }
252 
253 對形如/images/ef/uh7b3/test.png的請求,重寫到/data?file=test.png,於是匹配到location /data,先看/data/images/test.png文件存不存在,如果存在則正常響應,如果不存在則重寫tryfiles到新的image404 location,直接返回404狀態碼。
254 
255 例2:
256 
257 rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3? last;
258 對形如/images/bla_500x400.jpg的文件請求,重寫到/resizer/bla.jpg?width=500&height=400地址,並會繼續嘗試匹配location。

 

 

from:http://seanlook.com/2015/05/17/nginx-location-rewrite/


免責聲明!

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



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