Nginx rewrite指令用于URL重写,需在server或location块中配置,支持正则匹配与last、break、redirect、permanent等flag控制行为,如rewrite ^/old/(.*)$ /new/$1 permanent实现301重定向。

Nginx 使用 rewrite 指令实现 URL 路径重写,核心在于在 server 或 location 块中配置规则,配合正则匹配和重定向标志控制行为。
基本语法与位置要求
rewrite 必须写在 server、location 或 if 上下文中(不推荐在 if 中滥用)。语法为:
例如:
rewrite ^/old/(.*)$ /new/$1 permanent;这条规则把所有以 /old/ 开头的路径,重写为 /new/ 后接原路径剩余部分,并返回 301 重定向。
常用 flag 的作用区别
flag 决定重写后是否继续匹配或如何响应客户端:
- last:重写后停止当前 location 匹配,用新 URI 重新查找 location(内部重写,URL 不变)
- break:重写后停止所有 rewrite 处理,也不再查找新 location(适合简单路径替换)
- redirect:返回 302 临时重定向(浏览器地址栏会变)
- permanent:返回 301 永久重定向(利于 SEO)
实际常用场景示例
以下是在 location 块中典型用法:
- 去掉 URL 中的
.html后缀:
rewrite ^/(.*)\.html$ /$1 last; - 强制跳转到带 www 的域名:
if ($host = 'example.com') { rewrite ^(.*)$ https://www.example.com$1 permanent; } - 将 PHP 脚本请求统一交给 index.php 处理(类似 Laravel 的入口):
location / { try_files $uri $uri/ /index.php?$query_string; }(更推荐用try_files,但若需改写路径也可:
rewrite ^/api/(.*)$ /index.php?route=api/$1 last;)
注意事项与调试技巧
rewrite 规则容易因顺序或 flag 使用不当导致循环或失效:
- 规则按书写顺序执行,一旦匹配并带
last或break就终止当前阶段处理 - 避免在
if中做复杂 rewrite,Nginx 官方明确建议优先用location+rewrite或try_files - 开启
error_log /path/to/error.log notice;可查看 rewrite 执行日志(需编译时启用--with-debug并设置 debug 级别) - 测试时先用
redirect,确认逻辑正确后再换permanent











