和apache等web服務軟件同樣,rewrite的主要功能是實現URL地址的重定向。html
Nginx的rewrite功能須要PCRE軟件的支持,即經過perl兼容正則表達式語句進行規則匹配的。nginx
默認參數編譯nginx就會支持rewrite的模塊,可是也必需要PCRE的支持。web
Rewrite功能是Nginx服務器提供的一個重要功能。正則表達式
幾乎是全部的web產品必備技能,用於實現URL重寫。chrome
URL重寫是很是有用的功能,好比它能夠在咱們在改變網站結構後,不須要客戶端修改原來的書籤,也不須要其餘網站修改對咱們網站的友情連接,還能夠在必定程度上提升網站的安全性,可以讓咱們的網站顯得更專業。apache
域名變動 (京東)瀏覽器
用戶跳轉 (從某個鏈接跳到另外一個鏈接)緩存
僞靜態場景 (便於CDN緩存動態頁面數據)安全
URL 模塊語法服務器
set 設置變量 if 負責語句中的判斷 return 返回返回值或URL break 終止後續的rewrite規則 rewrite 重定向URL
set指令 自定義變量
Syntax: set $variable value; Default: — Context: server, location, if
將http://www.ayitula.com 重寫爲 http://www.ayitula.com/baism:
location / { set $name baism; rewrite ^(.*)$ http://www.ayitula.com/$name; }
if 指令 負責判斷
Syntax: if (condition) { ... } Default: — Context: server, location
條件匹配
模糊匹配 ~匹配 !~不匹配 ~* 不區分大小寫的匹配
精確匹配 = !=
location / { root html; index index.html index.htm; if ($http_user_agent ~* 'Chrome') { break; return 403; #return http://www.jd.com; } }
return 指令 定義返回數據
Syntax: return code [text]; return code URL; return URL; Default: — Context: server, location, if
location / { root html; index index.html index.htm; if ($http_user_agent ~* 'Chrome') { return 403; #return http://www.jd.com; } }
break 指令 中止執行當前虛擬主機的後續rewrite指令集
Syntax: break; Default:— Context:server, location, if
location / { root html; index index.html index.htm; if ($http_user_agent ~* 'Chrome') { break; return 403; } }
rewrite指令 實現重寫url
rewrite <regex> <replacement> [flag];
關鍵字 正則 替代內容 flag標記
flag:
last #本條規則匹配完成後,繼續向下匹配新的location URI規則
break #本條規則匹配完成即終止,再也不匹配後面的任何規則
redirect #返回302臨時重定向,瀏覽器地址會顯示跳轉後的URL地址
permanent #返回301永久重定向,瀏覽器地址欄會顯示跳轉後的URL地址
重定向就是將網頁自動轉向重定向,permanent和redirect從定向的區別
301永久性重定向:新網址徹底繼承舊網址,舊網址的排名等徹底清零
301重定向是網頁更改地址後對搜索引擎友好的最好方法,只要不是暫時搬移的狀況,都建議使用301來作轉址。
302臨時性重定向:對舊網址沒有影響,但新網址不會有排名
搜索引擎會抓取新的內容而保留舊的網址
permanent標誌:永久重定向
www.ayitula.com 重寫爲 www.jd.com server { listen 80; server_name www.ayitula.com; location / { rewrite ^/$ http://www.jd.com permanent; } }
redirect標誌:臨時重定向
域名跳轉 www.ayitula.com 重寫爲 www.jd.com server { listen 80; server_name www.ayitula.com; location / { rewrite ^/$ http://www.jd.com redirect; } }
break標誌: 相似臨時重定向
域名跳轉 www.ayitula.com 重寫爲 www.jd.com server { listen 80; server_name www.ayitula.com; location / { rewrite ^/$ http://www.jd.com break; } }
last標誌:
url重寫後,立刻發起一個新的請求,再次進入server塊,重試location匹配,超過10次匹配不到報500錯誤,地址欄url不變
last 通常出如今server或if中
根據用戶瀏覽器重寫訪問目錄
若是是chrome瀏覽器 就將 http://192.168.10.42/$URI 重寫爲 http://http://192.168.10.42/chrome/$URI 實現 步驟 1)URL重寫 2)請求轉給本機location location / { ..... if ($http_user_agent ~* 'chrome'){ #^ 以什麼開頭 ^a #$ 以什麼結尾 c$ #. 除了回車之外的任意一個字符 #* 前面的字符能夠出現屢次或者不出現 #更多內容看正則表達式 re rewrite ^(.*)$ /chrome/$1 last; } location /chrome { root html ; index index.html; } }