last终止当前location内后续rewrite,并用新uri重新匹配location;break则停止rewrite后继续执行当前location内其他指令,不重新匹配。

在 Nginx 的 rewrite 指令中使用 last 标记,不是“停止当前处理”,而是终止当前 location 块内的 rewrite 处理,并立即用新 URI 重新发起 location 匹配。它不会返回响应,也不会跳出整个请求流程,而是触发一次内部重定向(internal redirect)。
last 的作用机制
last 会:
- 丢弃当前 location 中后续所有 rewrite 指令(即使写在它后面也无效)
- 用 rewrite 后生成的新 URI,从头开始匹配
location块(包括前缀匹配、正则匹配等) - 不改变客户端看到的 URL(浏览器地址栏不变),是服务端内部行为
- 只在
server或location级别生效;不能在if块中直接使用(Nginx 1.19.0+ 允许部分 if + rewrite last,但依然不推荐)
和 break 的关键区别
break 是终止 rewrite 并继续执行当前 location 内剩余指令(比如 proxy_pass、root 等),不再重新匹配 location;而 last 是彻底跳出当前 location,用新 URI 找下一个最匹配的 location。
例如:
location /old/ {
rewrite ^/old/(.*)$ /new/$1 last;
}
location /new/ {
return 200 "hit /new/";
}
访问 /old/test 会返回 "hit /new/",因为 last 触发了对 /new/test 的 location 重匹配,命中了 /new/ 块。
实际使用建议
- 确保 rewrite 后的 URI 能被某个 location 正确捕获,否则可能进入
location /或返回 404 - 避免循环:如
rewrite /a/ /b/ last;和rewrite /b/ /a/ last;会触发 10 次重试后报 500 错误 - 如果目标是外部跳转(改浏览器地址),请用
redirect或permanent,不是last - 配合
alias或proxy_pass时注意路径拼接逻辑——last后进入新 location,其proxy_pass或root规则才真正生效
一个典型场景:前端单页应用(SPA)路由 fallback
让所有非静态资源请求都落到 index.html:
location / {
try_files $uri $uri/ @fallback;
}
location @fallback {
rewrite ^(.*)$ /index.html last;
}
当请求 /user/profile 且文件不存在时,进入 @fallback,rewrite ... last 把 URI 变成 /index.html,然后重新匹配 —— 最终由 location / 中的 try_files 正确服务该文件。











