rewrite_log仅在nginx≤1.18.x有效且需with-debug编译、notice级error_log配合;≥1.19.0须用error_log ... debug,并通过grep过滤重写相关日志行。

rewrite_log 不是独立生效的日志开关,它只是重写调试的“触发器”,真正输出日志依赖版本、编译支持、日志级别和作用域四者严格对齐。用错版本或漏配任一环节,日志就完全静默——这不是配置没写,而是条件没凑齐。
先确认你的 Nginx 是否支持 rewrite_log
这条指令自 Nginx 1.19.0 起已被正式废弃,只在 1.18.x 及更早版本中有效。别急着加配置,先执行两行命令:
-
nginx -v:若显示
nginx/1.18.0或更低,可继续;若为nginx/1.19.0及以上,rewrite_log 已不可用,必须改用error_log ... debug -
nginx -V 2>&1 | grep -o with-debug:无输出说明未编译 debug 模块,无论 rewrite_log 还是新版 debug 日志都无效,需重新编译并添加
--with-debug
旧版(≤1.18.x):rewrite_log + notice 级 error_log
满足版本和编译前提后,仅靠 rewrite_log on; 仍不会出日志。必须同步配置:
- 在
http或对应server块中写:rewrite_log on; - 在同一作用域(建议直接放在
http块)添加:error_log /var/log/nginx/rewrite.log notice; - 注意:日志级别必须是 notice,设成
info或debug会静默失效
重启后请求触发 rewrite,日志中会出现类似:
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
rewrite_log 指令已移除,等效能力由 error_log ... debug 提供,但要求更严、信息更全:
- 确保已编译
--with-debug(同上验证) - 配置:
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"
让日志真正帮你定位问题
单看日志容易误判哪条规则生效,建议三步联动:
- 用
curl -v http://localhost/path查响应头与状态码,确认是否跳转、内部重写或 404 - 对照日志中同一时间戳、相同连接符(如
*12345)的多行记录,还原完整执行流 - 在
http块定义:log_format debug_log '$remote_addr "$request" $status "$request_uri" "$uri" "$args"';,再启用access_log /var/log/nginx/access_debug.log debug_log;,比对原始请求与重写后变量值差异










