该指令通过正则表达式的使用来改变URI,可以同时存在一个或者多个指令,按照顺序依次对URL进行匹配和处理
rewrite 重写:和location类似,也是要负责URL解析的,和apache差别不大,主要使用正则表达式,可以把重写的规则放在location里面,也可以放在server里面。
常用的命令
if (条件) {} 设定条件,再进行重写
set #设置变量
return #返回状态码
break #跳出rewrite
rewrite #重写
If语法格式
if 空格 (条件){
重写模式
}
条件又怎么写?
1. “=”来判断相等, 用于字符串比较
2. “~” 用正则来匹配(此处的正则区分大小写)
~* 不区分大小写的正则
3. -f -d -e来判断是否为文件,为目录,是否存在.
[root@tiejiang ~]# cd /usr/local/nginx/
[root@tiejiang nginx]# vim html/test-if.html
<html>
test if and reutrn;
</html>
[root@tiejiang nginx]# tail -n 1 logs/access.log
192.168.0.102 - - [15/May/2018:03:53:36 +0800] "GET /test-if.html HTTP/1.1" 200 35 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"
拒绝一个指定IP访问这个Test-If.Html页面
[root@tiejiang ~]# cd /usr/local/nginx/
[root@tiejiang nginx]# vim conf/nginx.conf
location / {
if ($remote_addr = 192.168.0.102) {
return 403;
}
root html;
index index.html index.htm;
}
[root@tiejiang nginx]# ./sbin/nginx -s reload
拒绝IE浏览器打开任何页面(Msie是Ie的标识)
[root@tiejiang ~]# cd /usr/local/nginx/
[root@tiejiang nginx]# vim conf/nginx.conf
location / {
if ($http_user_agent ~ MSIE) {
rewrite ^.*$ /ie.html;
break;
}
root html;
index index.html index.htm;
}
[root@tiejiang nginx]# vim html/ie.html
<html>
amn ie, fuck.
</html>
用Rewrite设置404页面
[root@tiejiang ~]# cd /usr/local/nginx/
[root@tiejiang nginx]# vim html/404.html
<html>
this is 404
</html>
[root@tiejiang nginx]# vim conf/nginx.conf
location / {
if ($http_user_agent ~ MSIE) {
rewrite ^.*$ /ie.html;
break;
}
if (!-e $document_root$fastcgi_script_name){
rewrite ^.*$ /404.html;
break;
}
root html;
index index.html index.htm;
}
[root@tiejiang nginx]# ./sbin/nginx -s reload