nginx組態檔,rewrite,if
目錄- nginx組態檔,rewrite,if
- rewrit
- 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/518451.html
標籤:其他
下一篇:Ansible簡介
