nginx rewrite舉例詳解
1.標誌位,放在每一條規則的最後面
last : 相當於Apache的[L]標記,表示完成rewrite break : 停止執行當前虛擬主機的後續rewrite指令集,一旦匹配不再往後匹配 redirect : 返回302臨時重定向,位址列會顯示跳轉後的地址 permanent : 返回301永久重定向,位址列會顯示跳轉後的地址
2.全域性變數
全域性變數,可以直接在定義的規則中使用,不知道可以查
下面是可以用作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相同。
3.可能會用的幾個if判斷
if判斷指令 語法為if(condition){...},對給定的條件condition進行判斷。如果為真,大括號內的rewrite指令將被執行. 當表示式只是一個變數時,如果值為空或任何以0開頭的字串都會當做false 直接比較變數和內容時,使用=或!= ~正則表示式匹配,~*不區分大小寫的匹配,!~區分大小寫的不匹配 -f和!-f用來判斷是否存在檔案 -d和!-d用來判斷是否存在目錄 -e和!-e用來判斷是否存在檔案或目錄 -x和!-x用來判斷檔案是否可執行
4.案例,前面看不懂沒事,對著例子看,更容易懂
server { listen80; server_namewww.jd.com; access_loglogs/jd.access.logmain; if ($host = 'jd.com') { #將jd.com的所有請求全部轉到www.baidu.com,(.*)任意字串,後面$1對其進行引用,而且使用的是301永久重定向,url顯示跳轉後的地址 rewrite ^/(.*)$ http://www.baidu.com/$1 permanent; } location / { roothtml/jd.com; indexindex.html index.htm; } }
再來一個
server { listen80; server_namewww.jd.com; access_loglogs/jd.access.logmain; #301永久重定向訪問本域名將重定向到tao.bao,與上一個的區別是不再引用請求字串,不管你是請求的什麼,都直接跳到taobao下的index.html頁面 rewrite ^/(.*)$ http://www.taobao.com/index.html permanent; location / { roothtml/jd.com; indexindex.html index.htm; } }
再來一個
server { listen80; server_namewww.jd.com; access_loglogs/jd.access.logmain; #訪問 /test/ 將會被重定向到 /index.html ,且瀏覽器地址不變 rewrite ^/test/$ /index.html last; location / { roothtml/jd.com; indexindex.html index.htm; } }
最後一個:檔案禁止訪問
server { listen80; server_namewww.jd.com; access_loglogs/jd.access.logmain; location ~ .*\.(txt|db)$#對.txt,.db結尾的檔案不允許訪問 { return 403; } location / { roothtml/jd.com; indexindex.html index.htm; } }