rewrite可以寫在server段、location段和if段。語法:
rewrite regexp replacement [flag]
flag是標記。有4種標記,它們的作用如下表。
flag | 說明 |
---|---|
last | 停止處理當前上下文中的其他重寫模塊指令,並為重寫后的uri再次進行上下文的匹配 |
break | 和break指令一樣,都是停止處理當前上下文中的其他重寫模塊指令 |
redirect | 返回臨時重定向狀態碼302。當replacement部分不是以"http://"或者"https://"或者"$schema"開頭的時候使用,"$schema"變量表示使用的是什么協議 |
permanent | 返回永久重定向狀態碼301 |
注意:
last和break用來實現URL改寫,此時瀏覽器中的地址不會改變,但實際上在服務器上訪問的資源和路徑已經改變了。
redirect和permanent用來實現URL跳轉,瀏覽器中的地址會改變為跳轉后的地址。
在使用proxy_pass指令時要使用break標記。last標記在本條rewrite規則執行完后,繼續在當前上下文對重寫后的地址發起匹配請求,而break則在本次匹配完成后停止再次匹配。
例如下面的兩條重寫規則。
rewrite "^/bbs/(.*)/images/(.*)\.jpg$" www.linuxidc.com/bbs/$2/images/$1.jpg last; rewrite "^/bbs/(.*)/images/(.*)\.jpg$" www.linuxidc.com/bbs/$2/images/$1.jpg break;
如果訪問的是www.linuxidc.com/bbs/a/images/b.jpg則重寫后為www.linuxidc.com/bbs/b/images/a.jpg,
但是重寫后的地址仍然可以匹配到規則^/bbs/(.*)/images/(.*)\.jpg$
,此時如果使用last標記,則會再次進行重寫,最終導致URL重寫循環,nginx默認支持10次循環,然后返回500狀態碼。
而如果使用break標記,則在重寫完成后不會再次匹配重寫。
例子1. 在server字段中寫rewrite,使得任意以linuxidc.com結尾的訪問重定向到www.linuxidc.com。
server_name www.linuxidc.com;
rewrite (.*).linuxidc.com www.linuxidc.com permanent;
例子2. 在location字段中rewrite,使得localhost/bbs/*的訪問都重定向到localhost/forum/*。
server { listen 80; server_name localhost; location /bbs { root html/; index index.html; rewrite "/bbs/(.*)" "/forum/$1" last; } }
可以測試一下,比如nginx安裝目錄為:/usr/local/nginx,那么在/usr/local/nginx/html中新建2個文件夾,bbs和forum,並且分別在這兩個文件夾中都建立文件1.txt,分別寫入
hello, bbs
hello, forum
然后訪問http://localhost/bbs/1.txt, 可以看到返回hello, forum。 表示重寫成功
附加一個基於openrestry的https方案 https://www.cnblogs.com/shihuc/p/7150900.html