文章目录
rewrite
实验前提
部署nginx,关闭防火墙和selinux
常见的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 |
nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:
| 标识符 | 意义 |
|---|---|
| ^ | 必须以^后的实体开头 |
| $ | 必须以$前的实体结尾 |
| . | 匹配任意字符 |
| [] | 匹配指定字符集内的任意字符 |
| [^] | 匹配任何不包括在指定字符集内的任意字符串 |
| | | 匹配 | 之前或之后的实体 |
| () | 分组,组成一组用于匹配的实体,通常会有 | 来协助 |
网页重定向
需求:资源更改了位置,但是又要保证不更改用户的使用习惯
在/usr/local/nginx/html/下新建一个目录imgs并测试
[root@C85 ~]# cd /usr/local/nginx/html/
[root@C85 html]# mkdir imgs
向imgs目录中插入三张图片(我这边是直接在本地拖入的图片)
##没有tree命令就安装一个(dnf install -y tree)
[root@C85 html]# tree
.
├── 50x.html
├── imgs
│ ├── 1.jpg
│ ├── 2.jpg
│ └── 3.jpeg
└── index.html
去网页访问

修改目录名以后访问
[root@C85 html]# mv imgs images
[root@C85 html]# ls
50x.html images index.html

修改nginx配置文件然后测试访问
[root@C85 html]# vim /usr/local/nginx/conf/nginx.conf
location /imgs {
rewrite ^/imgs/(.*\.jpg|.*\.jpeg)$ /images/$1 break;
}
[root@C85 html]# nginx -s reload
现在两种方式都可以访问到

last应用
页面会跳转到百度
[root@C85 html]# vim /usr/local/nginx/conf/nginx.conf
location /imgs {
rewrite ^/imgs/(.*\.jpg|.*\.jpeg)$ /images/$1 last;
}
location /images {
rewrite ^/images/(.*\jpg|.*\jpeg)$ http://www.baidu.com break;
}
[root@C85 html]# nginx -s reload

redirect
[root@C85 html]# vim /usr/local/nginx/conf/nginx.conf
location /imgs {
rewrite ^/imgs/(.*\.jpg|.*\.jpeg)$ /images/$1 redirect;
}
[root@C85 html]# nginx -s reload

permanent
[root@C85 html]# vim /usr/local/nginx/conf/nginx.conf
location /imgs {
rewrite ^/imgs/(.*\.jpg|.*\.jpeg)$ /images/$1 permanent;
}
[root@C85 html]# nginx -s reload

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;
}
}
版权声明:本文为happy___life原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。