rewrite_log on 本身不输出日志,需搭配 notice 级 error_log 才生效;旧版(≤1.18.x)依赖 --with-debug 编译与作用域对齐,新版(≥1.19.0)须改用 debug 日志,并结合 access_log 与 log_format 还原重写全流程。

rewrite_log on 本身不输出日志,必须搭配正确配置的 error_log 才能生效;它不是独立开关,而是依赖版本、编译支持、日志级别和作用域四要素对齐才能精准追踪重写路径。
确认 Nginx 版本与 debug 编译支持
先验证环境是否满足基础条件:
- 运行 nginx -v:若版本 ≤ 1.18.x(如 nginx/1.18.0),rewrite_log 指令可用;若 ≥ 1.19.0,则该指令已废弃,必须改用 debug 日志
- 运行 nginx -V 2>&1 | grep -o with-debug:无输出说明未启用 --with-debug 编译,rewrite_log(旧版)或 debug 日志(新版)均无法工作,需重编译并添加该参数
旧版本(≤1.18.x):配置 rewrite_log + notice 级 error_log
仅在满足编译支持的前提下生效,且日志级别必须为 notice:
- 在 http 块(最稳妥)或对应 server 块中同时写入:
rewrite_log on;
error_log /var/log/nginx/rewrite.log notice; - 不能设为 info 或 debug 级别,否则静默失效
- 确保该 error_log 的作用域覆盖到实际执行 rewrite 的 location —— 放在 http 块可避免遗漏
- 重启 Nginx 后触发请求,日志中会出现类似:
2026/05/01 08:45:22 [notice] 1234#1234: "^/api/v(\d+)/(.+)$" matches "/api/v1/users", client: 127.0.0.1
新版本(≥1.19.0):启用 debug 日志替代 rewrite_log
信息更全、逻辑更透明,但要求更严格:
- 确认已编译 --with-debug(同上验证)
- 在 http 块中配置:
error_log /var/log/nginx/debug.log debug; - 重启后,所有重写动作都会记录,例如:
"using regex "^/old/(.*)$" rewritten data: "/new/$1"
"test location: "/new/" matched location: /new/" - 实时过滤关键行:
tail -f /var/log/nginx/debug.log | grep -i "rewrite\|regex\|location"
结合 access_log + log_format 还原真实执行流
单看重写日志容易误判最终生效规则,建议联动观察原始请求与重写结果:
- 在 http 块定义清晰的调试格式:
log_format debug_log '$remote_addr "$request" $status "$request_uri" "$uri" "$args"'; - 启用对应 access_log:
access_log /var/log/nginx/access_debug.log debug_log; - 用 curl -v 发起请求,比对 access_debug.log 中的 $request_uri(原始)与 $uri(重写后)差异
- 对照 debug.log 或 rewrite.log 中同一时间戳、相同连接标识(如 *12345)的多行记录,还原完整匹配-重写-跳转链路



















