rewrite_log仅在Nginx≤1.18.x有效,需四点对齐:版本适配、--with-debug编译、error_log设为notice级、作用域覆盖rewrite所在location;≥1.19.0须改用error_log debug配合grep过滤。

rewrite_log 不是独立生效的日志开关,它只是重写调试的“触发器”。真正输出日志依赖版本、编译支持、日志级别和作用域四者严格对齐。用错版本或漏配任一环节,日志就完全静默——这不是配置没写,而是条件没凑齐。
确认 Nginx 版本与 debug 编译支持
先执行两行命令验证基础环境:
-
nginx -v:若显示
nginx/1.18.0或更低,rewrite_log 可用;若为nginx/1.19.0及以上,该指令已移除,必须改用error_log debug -
nginx -V 2>&1 | grep -o with-debug:无输出说明未启用 debug 模块,无论新旧版本,重写日志都不可用,需重新编译并添加
--with-debug
旧版(≤1.18.x):启用 notice 级 rewrite 日志
rewrite_log on 本身不产生日志,必须配合特定 error_log 配置:
- 在
http块(推荐)或对应server块中同时写:rewrite_log on;error_log /var/log/nginx/rewrite.log notice; - 日志级别必须是 notice,设为 info 或 debug 会静默失效
- 确保该
error_log作用域覆盖到实际执行 rewrite 的 location(例如放在 http 块最安全)
重启后请求触发,日志中会出现类似:2026/05/01 08:45:22 [notice] 1234#1234: "^/api/v(\d+)/(.+)$" matches "/api/v1/users", client: 127.0.0.1
新版(≥1.19.0):用 error_log debug 替代 rewrite_log
rewrite_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 与自定义 access_log 定位真实执行路径
单看重写日志容易误判哪条规则最终生效,建议三步联动:
- 用
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;
可比对原始请求与重写后变量值差异

















