目录
在 location 中加入 break 和 last (不一样)
在 server 中加入 break 和 last (一样)
rewrite 作用:
域名跳转(重定向)
URL重写(伪静态)(一长串参数很复杂的链接 跳转 到简介的链接上)
动静分离(跳转域名然后接入CDN实现加速,
这种情况较多,对于大流量的网站相对鸡肋,但对于小网站很实用)
依赖:
PCRE库 ,因为要用到正则表达式
ngx_http_rewrite_module 需要编译入的模块
配置 rewrite重定向日志:
1) rewrite_log on;
![](https://img-blog.csdnimg.cn/91353f4bfdad4cba849ccc91614d1611.png)
2)错误日志中 必须
开启 notice 记录等级
,然后rewrite会被写入到error.log中
![](https://img-blog.csdnimg.cn/f873e03d3559445286f0ae5b3c4f589c.png)
if 判断
依靠nginx内置非自定义变量, 如 $request_method、 request_uri
逻辑判断符号
~ 匹配(正则表达式) ~
*
不区分大小写匹配(正则表达式)
匹配的字符串可以是正则表达式,通常不用加引号,仅在表达式中有特殊符号( 空格、花括号、分号等时)用单引号括起来。
-
限制 请求方式 为post
![](https://img-blog.csdnimg.cn/c0c3465b23144aa68f6e9b5f810666e9.png)
-
限制 请求的浏览器 为 MSIE或firefox或spider
当不确定浏览器名时候可以用 ~* 来忽略大小写。
![](https://img-blog.csdnimg.cn/cd277630f671497583eef670501fadbc.png)
-
限制 当请求的文件 不存在时候
![](https://img-blog.csdnimg.cn/44194af0b0b0400581245960d7ffd68e.png)
-
限制 URL中gid包含9-12个数字
\d 代表数字 {9,12} 代表范围 ,即当 gid 等于 9至12个数字开头,/ 结尾,的时候就是符合的。
![](https://img-blog.csdnimg.cn/6f34885f72864f82833966bbc00dbd60.png)
location {} 本身有反复匹配执行特征
如下,当是www.lwjweb.com/1.html 时候,会先匹配 location / 里的变为 www.
lwjweb.com/3.html —— 出来匹配到 /3.html 变为 www.
lwjweb.com/a.html 。 这时候又会从头匹配到 location / ,只是进去以后没有对应的rewrite ,这时匹配才结束。
server {
location / {
rewrite /1.html /2.html ;
rewrite /2.html /3.html ;
}
location /3.html {
rewrite a.html
}
}
例:
rewrite 一个1.html转2.html ,2.html转3.html的例子
多个rewrite会根据上一步结果依次执行
![](https://img-blog.csdnimg.cn/7b2f2b5022a046be8bcf67249458d40d.png)
![](https://img-blog.csdnimg.cn/35912fcfe37549e180c8ea82065bcbfe.png)
![](https://img-blog.csdnimg.cn/21e9ab266b9d46f191e7165a12b56e23.png)
错误日志中可见,1.html 匹配到了/1.html 转换为了2.html,2.html 匹配到了/2.html 转换为了3.html,
3.html 最后还再次匹配进了 / ,进行了 /1.html 和 /2.html 的对比,但是没有匹配成功。
![](https://img-blog.csdnimg.cn/dd5bca499a734166897f6fb78c625766.png)
break、last 可
用来防止反复rewrite
在 location 中加入 break 和 last (不一样)
-
加了break后,立刻停止向下 且 跳出。
不但这个location不会执行,外面的其他location也不会执行,就此停止。
![](https://img-blog.csdnimg.cn/a9a42d64b62d4a89ad7ffe0cb9b11839.png)
![](https://img-blog.csdnimg.cn/679d1b79c06a499cb7c1c120976ad1d8.png)
-
加了last,会停止当前向下后,会重头再来一遍。
![](https://img-blog.csdnimg.cn/e32862bde47049c4913c6ccc518f6ff8.png)
![](https://img-blog.csdnimg.cn/8e7f3c969315450aaa53731a6affa944.png)
![](https://img-blog.csdnimg.cn/a094980a94a64dbd8de6bea6a40daba4.png)
server {
location / {
rewrite /1.html /2.html last;
rewrite /2.html /3.html ;
}
location /2.html {
rewrite a.html
}
}
#结果是/a.html
当是
www.lwjweb.com/1.html 时候,会先匹配 location / 里的 /1.html 的变为 www.
lwjweb.com/2.html ,被 last 打断,重头再来,再同时匹配到 / 和 /2.html ,但因为/2.html 更为准确因此会走 /2.html ,变为 www.
lwjweb.com/a.html 。 这时候又会从头匹配到 location / ,只是进去以后没有对应的rewrite ,这时匹配才结束。
![](https://img-blog.csdnimg.cn/b22ec739ba214cc5aff86d091f5aead6.png)
在 server 中加入 break 和 last (一样)
不在location中的话,2个都不会重复运行。
![](https://img-blog.csdnimg.cn/6a51dd63cefa4ccb88b94b750c502fe6.png)
![](https://img-blog.csdnimg.cn/faabd8ea663d4fa4961a38391d8a9909.png)