rewrite语法
rewrite <正则表达式> <跳转后的内容> [rewrite支持的flag标记]
常用正则表达式
^:匹配输入字符串的起始位置
$:匹配输入字符串的结束位置
*****:匹配前面的字符零次或多次
+:匹配前面的字符一次或多次
?:匹配前面的字符零次或一次
.:匹配除\n之外的任何单个字符 使用[.\n]可以匹配包括\n在内的任意字符
****:转义符
\d:匹配纯数字
{n}:重复n次
{n,}:重复n次或更多次
[c]:匹配单个字符c
[a-z]:匹配a-z小写字母的任意一个
[a-zA-Z]:匹配a-z小写字母或A-Z大写字母的任意一个
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重写flag
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
root /hhh/xxx;
location / {
rewrite /1.html /2.html;
rewrite /2.html /3.html;
}
location /2.html {
rewrite /2.html /a.html;
}
location /3.html {
rewrite /3.html /b.html;
}
[root@nginx ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful[root@nginx ~]# systemctl restart nginx
[root@nginx ~]# mkdir -p /hhh/xxx
[root@nginx ~]# echo "web1" > /hhh/xxx/1.html
[root@nginx ~]# echo "web2" > /hhh/xxx/2.html
[root@nginx ~]# echo "web3" > /hhh/xxx/3.html
[root@nginx ~]# echo "web a" > /hhh/xxx/a.html
[root@nginx ~]# echo "web b" > /hhh/xxx/b.html
[root@nginx ~]# curl 192.168.253.134/1.html
web b
当请求1.html时 最后会访问到web b,在location{}内部遇到break,本location{}内以及后面的所有location{}内的所有指令都不再执行,所以跳转到2.html访问web2
location / {
rewrite /1.html /2.html break;
rewrite /2.html /3.html;
}
location /2.html {
rewrite /2.html /a.html;
}
location /3.html {
rewrite /3.html /b.html;
}
[root@nginx ~]# curl 192.168.253.134/1.html
web2
location{}内部遇到last 本location{}内后续指令不执行 重写后的url会对所在server{…}标签重新发起请求
location / {
rewrite /1.html /2.html last;
rewrite /2.html /3.html;
}
location /2.html {
rewrite /2.html /a.html;
}
location /3.html {
rewrite /3.html /b.html;
}
[root@nginx ~]# curl 192.168.253.134/1.html web a
if
判断条件
==:等值比较;
~:与指定正则表达式模式匹配时返回“真”,判断匹配与否时区分字符大小写;
~*:与指定正则表达式模式匹配时返回“真”,判断匹配与否时不区分字符大小写;
!~:与指定正则表达式模式不匹配时返回“真”,判断匹配与否时区分字符大小写;
!~*:与指定正则表达式模式不匹配时返回“真”,判断匹配与否时不区分字符大小写
文件和目录匹配判断
-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;
}
}