nginx配置文件,rewrite,if rewrit 語法:rewrite regex replacement flag; 比如 rewrite ^/images/(.*\.jpg)$ /imgs/$1 break; 又如 rewrite ^/bbs/(.*)$ http://www.idfsof ...
nginx配置文件,rewrite,if
目錄rewrit
語法:rewrite regex replacement flag;
比如
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
又如
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;
如上例所示,replacement可以是某個路徑,也可以是某個URL
常見的flag
flag | 作用 |
---|---|
last | 基本上都用這個flag,表示當前的匹配結束,繼續下一個匹配,最多匹配10個到20個 一旦此rewrite規則重寫完成後,就不再被後面其它的rewrite規則進行處理 而是由UserAgent重新對重寫後的URL再一次發起請求,並從頭開始執行類似的過程 |
break | 中止Rewrite,不再繼續匹配 一旦此rewrite規則重寫完成後,由UserAgent對新的URL重新發起請求, 且不再會被當前location內的任何rewrite規則所檢查 |
redirect | 以臨時重定向的HTTP狀態302返回新的URL |
permanent | 以永久重定向的HTTP狀態301返回新的URL |
rewrite模塊的作用是用來執行URL重定向。這個機制有利於去掉惡意訪問的url,也有利於搜索引擎優化(SEO)
nginx使用的語法源於Perl相容正則表達式(PCRE)庫,基本語法如下:
標識符 | 意義 |
---|---|
^ | 必須以^後的實體開頭 |
$ | 必須以$前的實體結尾 |
. | 匹配任意字元 |
[] | 匹配指定字元集內的任意字元 |
[^] | 匹配任何不包括在指定字元集內的任意字元串 |
| | 匹配 | 之前或之後的實體 |
() | 分組,組成一組用於匹配的實體,通常會有 | 來協助 |
rewrit應用
#進入預設主頁創建一個目錄上傳一張圖片
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# ls
50x.html index.html
[root@localhost html]# mkdir images
[root@localhost html]# cd images/
[root@localhost images]# ls
dog.jpg
瀏覽器訪問
#修改images的名稱
[root@localhost images]# cd ..
[root@localhost html]# mv images imgs
[root@localhost html]# ls
50x.html imgs index.html
#此時用以前的訪問方式訪問不到
[root@localhost html]# curl 192.168.118.129/images/dog.jpg
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>
#配置nginx.conf文件,讓我們用以前的訪問方式也可以訪問到
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
...
location / {
root html;
index index.html index.htm;
}
#編寫下麵內容
location /images {
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
}
...
[root@localhost html]# systemctl restart nginx
此時再用以前的訪問方式在瀏覽器上訪問
重寫URL
#此時只要訪問/images/下的內容就會重寫到添加的URL上
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
...
location /images {
rewrite ^/images/(.*\.jpg)$ https://c-ssl.duitang.com/uploads/item/201301/16/20130116230750_FBfRF.jpeg break;
}
...
[root@localhost html]# systemctl restart nginx
再次訪問
if
語法:if (condition) {...}
應用場景:
- server段
- location段
常見的condition
- 變數名(變數值為空串,或者以“0”開始,則為false,其它的均為true)
- 以變數為操作數構成的比較表達式(可使用=,!=類似的比較操作符進行測試)
- 正則表達式的模式匹配操作
- ~:區分大小寫的模式匹配檢查
- ~*:不區分大小寫的模式匹配檢查
- !和!*:對上面兩種測試取反
- 測試指定路徑為文件的可能性(-f,!-f)
- 測試指定路徑為目錄的可能性(-d,!-d)
- 測試文件的存在性(-e,!-e)
- 檢查文件是否有執行許可權(-x,!-x)
基於瀏覽器實現分離案例
if ($http_user_agent ~ Firefox) {
rewrite ^(.*)$ /firefox/$1 break;
}
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
if ($http_user_agent ~ Chrome) {
rewrite ^(.*)$ /chrome/$1 break;
}
防盜鏈案例
location ~* \.(jpg|gif|jpeg|png)$ {
valid_referers none blocked www.idfsoft.com;
if ($invalid_referer) {
rewrite ^/ http://www.idfsoft.com/403.html;
}