nginx的rewrite理解起來也挺費勁
這周三,有個老同事和我討論了一個 HTTPS 問題,實質(zhì)上卻是 Nginx 的 rewrite 規(guī)則問題,我仔細閱讀了官方文檔,發(fā)現(xiàn)解釋的不是特別明了,逐寫了這篇博文。
rewrite 的語法規(guī)則如下:
Syntax: rewrite regex replacement [flag]; Context: server, location, if
我們暫時不考慮 flag 參數(shù),先從簡單的說起,首先務(wù)必要理解的就是 rewrite 規(guī)則在 server 段和 location 段中語義是不一樣的。
在一個 URL 請求中,rewrite 如果匹配到 regex,那么 URL 就會替換成 replacement,如果不考慮 flag,匹配規(guī)則是順序執(zhí)行的,即使匹配到了,仍然會繼續(xù)匹配下去。
記住,如果 replacement 包含 “http://”, “https://”, or “$scheme”,那么匹配會理解終止,并直接重定向地址給客戶端。
接下去說說 flag 可選參數(shù),如果有 flag 參數(shù),rewrite 會進一步處理指令。flag 參數(shù)有四個:
last:stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;
break:stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
redirect:returns a temporary redirect with the 302 code;
permanent:returns a permanent redirect with the 301 code.
flag 參數(shù)如果是 redirect 或 permanent,那么處理就相對簡單,立刻中止規(guī)則匹配,進行 302 或 301 跳轉(zhuǎn)。
從文檔看,last 和 break 看不出太大區(qū)別,我總結(jié)就是如果在 location 中配置 flag 是 last,立刻跳出本 location 的匹配,同時會順序繼續(xù)搜尋其他 location 的匹配,如果還沒匹配到,還會繼續(xù)搜尋本 location;而 break 跳出本 location 后就不會再匹配其它 location 了。通過個例子說明:
如果訪問 https://www.simplehttps.com/a/,則返回 401;如果訪問 https://www.simplehttps.com/b/,則返回 402。
接下去修改配置:
結(jié)果就是,不管訪問 https://www.simplehttps.com/a/ 還是 https://www.simplehttps.com/b/,都返回 404。
那么如果 flag 配置在 server 段內(nèi),會發(fā)生什么呢?不管是 break 還是 last,其行為規(guī)則是一樣的,不會有跳出的行為,會順序執(zhí)行。
那么文檔中描述的死循環(huán)什么情況呢?以下的例子在 location 中就會死循環(huán):
原因就在于 rewrite 匹配后還是 /download 開頭,如果是 last,會繼續(xù)走到 location /download/ { 段內(nèi),從而會死循環(huán),最終產(chǎn)生 500 錯誤,所以這種情況下,建議將 last 修改為 break。
其實事情也沒有那么復雜,取決于你清楚自己想達到什么目標,然后在 last 和 break 之間取舍。
我的書《深入淺出HTTPS:從原理到實戰(zhàn)》代碼實例已經(jīng)更新到 github 上了,地址是 https://github.com/ywdblog/httpsbook,歡迎一起討論。也歡迎關(guān)注我的公眾號(ID:yudadanwx,虞大膽的嘰嘰喳喳)。
本文轉(zhuǎn)載自異步社區(qū)。
Nginx
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔相應(yīng)法律責任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。