上一篇博文對nginx最經常使用功能的server及location的匹配規則進行了講解,這也是nginx實現控制訪問和反向代理的基礎。掌握請求的匹配規則算是對nginx有了入門,可是這些每每仍是不能知足實際的需求場景,例如請求url重寫、重定向等等,這都須要對請求的path
進行修改操做的,匹配規則是不能獨自完成實際需求的,這就須要掌握nginx的另外一個經常使用功能rewrite,下面就來講說這個經常使用功能。php
rewrite功能就是,使用nginx提供的全局變量或本身設置的變量,結合正則表達式和標誌位實現url重寫以及重定向。
rewrite只能放在server{}
, location{}
, if{}
中,而且只能對域名後邊傳遞的參數外的字符串起做用,例如 http://baidu.com/a/we/index.php?id=1&u=str 只對/a/we/index.php重寫。語法:html
rewrite regex replacement [flag];nginx
若是相對域名或參數字符串起做用,可使用全局變量匹配,也可使用proxy_pass反向代理。正則表達式
表面上看rewrite和location功能有點像,都能實現跳轉,主要區別在於rewrite是在同一域名內更改獲取資源的路徑,而location是對一類路徑作控制訪問或反向代理,能夠proxy_pass到其餘機器。不少狀況下rewrite也會寫在location裏,它們的執行順序是:segmentfault
若是其中某步URI被重寫,則從新循環執行1-3,直到找到真實存在的文件;循環超過10次,則返回500 Internal Server Error錯誤。服務器
last
: 中止執行當前ngx_http_rewrite_module
的指令集,可是會繼續走一遍請求匹配對應server或者location;break
: 中止執行當前ngx_http_rewrite_module
的指令集,請求就此完成。redirect
: 返回302臨時重定向,地址欄會顯示跳轉後的地址permanent
: 返回301永久重定向,地址欄會顯示跳轉後的地址由於301和302不能簡單的只返回狀態碼,還必須有重定向的URL,這就是return指令沒法返回301,302的緣由了。cookie
對於上面的flag,有幾點須要強調一下:curl
last
與break
對url的重寫不會改變地址欄的地址也就是說,nginx雖然對請求url進行了重寫,可是地址欄不會有任何明顯的改變,仍然顯示nginx重寫前的地址;這與redirect
和permanent
不一樣。ide
last
與break
的處理策略不一樣兩者都會終止當前ngx_http_rewrite_module
的指令集的執行,可是 last
當即發起新一輪的 請求匹配 而 break
則不會。post
redirect
和permanent
會終止後續nginx指令的執行nginx在rewrite遇到flag是兩者時,後續的指令是不會執行的。
server { listen 8080; location = /test { break; return 200 $request_uri; proxy_pass http://127.0.0.1:8080/other; } location / { return 200 $request_uri; } }
上面例子中,咱們訪問 curl 127.0.0.1:8080/test,會發現,return 200 $request_uri語句沒有執行,而proxy_pass
指令被執行了。這是由於:
return
指令屬於ngx_http_proxy_module模塊,它會被break終止掉;而rewrite模塊它是ngx_http_proxy_module的指令,不會被break
給中斷掉。
if判斷指令
語法爲if(condition){...}
,對給定的條件condition進行判斷。若是爲真,大括號內的rewrite指令將被執行,if條件(conditon)能夠是以下任何內容:
=
或!=
~
正則表達式匹配,~*
不區分大小寫的匹配,!~
區分大小寫的不匹配-f
和!-f
用來判斷是否存在文件
-d
和!-d
用來判斷是否存在目錄
-e
和!-e
用來判斷是否存在文件或目錄
-x
和!-x
用來判斷文件是否可執行
例如:
if ($http_user_agent ~ MSIE) { rewrite ^(.*)$ /msie/$1 break; } //若是UA包含"MSIE",rewrite請求到/msid/目錄下 if ($http_cookie ~* "id=([^;]+)(?:;|$)") { set $id $1; } //若是cookie匹配正則,設置變量$id等於正則引用部分 if ($request_method = POST) { return 405; } //若是提交方法爲POST,則返回狀態405(Method not allowed)。return不能返回301,302 if ($slow) { limit_rate 10k; } //限速,$slow能夠經過 set 指令設置 if (!-f $request_filename){ break; proxy_pass http://127.0.0.1; } //若是請求的文件名不存在,則反向代理到localhost 。這裏的break也是中止rewrite檢查 if ($args ~ post=140){ rewrite ^ http://example.com/ permanent; } //若是query string中包含"post=140",永久重定向到example.com location ~* \.(gif|jpg|png|swf|flv)$ { valid_referers none blocked www.jefflei.com www.leizhenfang.com; if ($invalid_referer) { return 404; } //防盜鏈 }
下面是能夠用做if判斷的全局變量:
$args
: #這個變量等於請求行中的參數,同$query_string$content_length
: 請求頭中的Content-length字段。$content_type
: 請求頭中的Content-Type字段。$document_root
: 當前請求在root指令中指定的值。$host
: 請求主機頭字段,不然爲服務器名稱。$http_user_agent
: 客戶端agent信息$http_cookie
: 客戶端cookie信息$limit_rate
: 這個變量能夠限制鏈接速率。$request_method
: 客戶端請求的動做,一般爲GET或POST。$remote_addr
: 客戶端的IP地址。$remote_port
: 客戶端的端口。$remote_user
: 已經通過Auth Basic Module驗證的用戶名。$request_filename
: 當前請求的文件路徑,由root或alias指令與URI請求生成。$scheme
: HTTP方法(如http,https)。$server_protocol
: 請求使用的協議,一般是HTTP/1.0或HTTP/1.1。$server_addr
: 服務器地址,在完成一次系統調用後能夠肯定這個值。$server_name
: 服務器名稱。$server_port
: 請求到達服務器的端口號。$request_uri
: 包含請求參數的原始URI,不包含主機名,如:」/foo/bar.php?arg=baz」。$uri
: 不帶請求參數的當前URI,$uri不包含主機名,如」/foo/bar.html」。$document_uri
: 與$uri相同。例如:
例:http://localhost:88/test1/test2/test.php $host:localhost $server_port:88 $request_uri:http://localhost:88/test1/test2/test.php $document_uri:/test1/test2/test.php $document_root:/var/www/html $request_filename:/var/www/html/test1/test2/test.php
.
: 匹配除換行符之外的任意字符?
: 重複0次或1次+
: 重複1次或更屢次*
: 重複0次或更屢次\d
:匹配數字^
: 匹配字符串的開始$
: 匹配字符串的結束{n}
: 重複n次{n,}
: 重複n次或更屢次[c]
: 匹配單個字符c[a-z]
: 匹配a-z小寫字母的任意一個小括號()
之間匹配的內容,能夠在後面經過$1
來引用,$2
表示的是前面第二個()裏的內容。正則裏面容易讓人困惑的是\
轉義特殊字符。
例1:
http { # 定義image日誌格式 log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status; # 開啓重寫日誌 rewrite_log on; server { root /home/www; location / { # 重寫規則信息 error_log logs/rewrite.log notice; # 注意這裏要用‘’單引號引發來,避免{} rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4; # 注意不能在上面這條規則後面加上「last」參數,不然下面的set指令不會執行 set $image_file $3; set $image_type $4; } location /data { # 指定針對圖片的日誌格式,來分析圖片類型和大小 access_log logs/images.log mian; root /data/images; # 應用前面定義的變量。判斷首先文件在不在,不在再判斷目錄在不在,若是還不在就跳轉到最後一個url裏 try_files /$arg_file /image404.html; } location = /image404.html { # 圖片不存在返回特定的信息 return 404 "image not found\n"; } }
對形如/images/ef/uh7b3/test.png
的請求,重寫到/data?file=test.png
,因而匹配到location /data
,先看/data/images/test.png
文件存不存在,若是存在則正常響應,若是不存在則重寫tryfiles到新的image404 location,直接返回404狀態碼。
例2:
rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3? last;
對形如/images/bla_500x400.jpg
的文件請求,重寫到/resizer/bla.jpg?width=500&height=400
地址,並會繼續嘗試匹配location。
例3:
見 ssl部分頁面加密 。
上面說過,rewrite的指令規則爲:rewrite regex replacement [flag];
rewrite指令用指定的regex來匹配請求的uri,若匹配成功則用replacement來重寫請求uri。這裏須要注意的replacement字符串的內容:
一、 若replacement以http://
、https://
或者$scheme
開頭,則告訴nginx這是重定向操做(flag默認爲redirect),nginx則中止處理後續內容,並直接重定向返回給客戶端。
location / { # 當匹配 正則表達式 /test/(.*)時 請求將被臨時重定向到 http://www.baidu.com/$1 # flag默認爲redirect rewrite /test/(.*) https://www.baidu.com/$1; return 200 ’ok'; # 此處沒有機會執行 }
二、replacement非以上三種狀況開頭,則就是簡單的url重寫
location / { # 當匹配 正則表達式 /test/(.*)時 請求將被臨時重定向到 www.baidu.com/$1 # flag無值則rewrite會順序執行 rewrite /test/(.*) www.baidu.com/$1; return 200 ’ok'; # 此處由於rewrite順序執行而獲得執行機會 }
對於上面兩種狀況,還須要特別留意一個redirect端口的問題,先上一個例子:
## server.com機器上nginx的配置以下: server { listen 8000; location /test1/ { rewrite /test1/index.html http://server1.com/demo/test1 redirect; } location /test2/ { rewrite /test2/index.html /demo/test2 redirect; proxy_pass http://192.168.1.3:8000; } }
當訪問http://server.com/test1/index.html時,會命中/test1的location規則,訪問server1.com對應內容一直失敗,發現重定向後響應頭的Location
字段值爲http://server1.com:8000/demo/test1,帶有8000端口,咱們並無配置,表現的比較詭異?
訪問http://server.com/test2/index.html時,命中/test2的location規則,一樣訪問失敗,可是訪問的重定向後響應頭Location
字段值爲http://server.com:8000/demo/test2,其帶有server.com的server_name和8000的端口,更加詭異?
看到上面的現象,疑惑重重;其實這跟nginx的server_name_in_redirect
和port_in_redirect
指令有關:
在絕對路徑中,
server_name_in_redirect
和port_in_redirect
指令表示是否將server塊中的 server_name 和 listen 的端口做爲redirect用, 重定向的完整url地址根據$scheme
跟server_name_in_redirect
和port_in_redirect
來肯定的。
在絕對路徑中,server_name_in_redirect
默認是禁用的,而port_in_redirect
是默認啓用的。對於帶有$scheme
重定向的絕對路徑,nginx會從replacement中獲取指定的server_name和port來進行重定向:
第一種,若replacement帶請求協議http(s),而其中沒有指定port的話,nginx會默認取當前server的listen端口做爲重定向的端口。這是上面訪問http://server.com/test1/index.html時重定向到http://server.com:8000/demo/test2時會攜帶8000的緣由。
第二種,若replacement不帶請求協議http(s),而是相對本地服務器的絕對地址的話,如上面訪問http://server.com/test2/index.html的狀況,此時server_name_in_redirect
因爲禁用它會去請求的host來做爲server_name,取當前server的listen端口做爲重定向的端口,最終重定向到http://server.com:8000/demo/test2。
或許你會問,訪問http://server.com/test2/index.html爲何不會重定向到http://192.168.1.3:8000/demo/test2上?這是由於rewrite的redirect flag會終止後續指令的執行,因此其後的proxy_pass
指令不會執行。