nginx中return和rewrite指令同时存在,先执行顺序哪个?

黎小强
2021-01-28 / 0 评论 / 739 阅读 / 正在检测是否收录...

前文

如果return指令rewrite指令同时存在先执行哪个呢?

场景示例

模拟数据
server {
    location /images {
        rewrite /images/(.*)$ /pic/$1 last;  
        return 200 "return 200 in /images";
    }
    
    location /pic {
         rewrite /pic/(.*) /photos/$1;
         return 200 "return 200 in /pic";
    }
    
    location /photos {
        return 200 "return 200 in /photos";
        
    }
}

分别在/images/pic/photos的location段增加return 返回200状态码并输出字符串

流程

  1. 访问xxx.com/images/index.html ,会进入/images的location段中
  2. /images中,进行rewrite指令,将images/index.html重写到/pic/的index.html,并且有last 值
  3. 遇到last值,会重新触发请求。在server段/pic的location段。
  4. 匹配到location的/pic后 ,又重写,将/pic的index.html重定向到/photos目录下的index.html。(注意/pic段没有加last值,意味着流程顺序执行!
  5. 没有加flag标签。所以/pic段中依然执行下面的命令,会走retrun 200 "return 200 in /pic" 之后就中断。

1.jpg

2.jpg

场景2

如果在/pic段中增加flag的break,会执行什么?

3.jpg

当遇到break,会重写找/photos段,不会执行return 200 in /pic

4.jpg


注意事项

如果当你直接访问xxx.com/photos/index.html, 但是又有return指令会优先执行return指令 , 并不会返回photos/index.html的页面,直接返回return结果给你。

如果没有return指令才会找目录对应下的有没有index.html文件。

5.jpg

0

评论 (0)

取消