nginx rewrite调试需依版本选择日志方案:≤1.18.x用rewrite_log,≥1.19.0须启用debug日志且需--with-debug编译;日志必须置于rewrite作用域上级,关键看matches、rewritten data、using regex等字段,并辅以debug location和map验证。

调试 Nginx 请求路径 rewrite,核心是看清“实际匹配了哪条规则、是否捕获成功、替换后去了哪里”。它不是靠猜,而是靠日志+作用域+验证三者闭环。
先确认你的 Nginx 版本和编译能力
rewrite_log 在 1.19.0 及以后版本已被移除,新版必须依赖 debug 日志;旧版(如 1.18.x)才能用 rewrite_log。关键检查两步:
- 运行 nginx -v 看版本号:≤1.18.x 才能用 rewrite_log;≥1.19.0 必须走 debug 路径
- 运行 nginx -V 2>&1 | grep with-debug:无输出说明没编译 debug 模块,debug 日志无法启用
按版本选择对应日志配置
日志不是开了就有效,必须配对且作用域正确:
-
≤1.18.x 版本:在 http/server/location 块中同时写
rewrite_log on;
error_log /var/log/nginx/rewrite.log notice; -
≥1.19.0 版本:确保带 --with-debug 编译后,在 http 或 server 块中写
error_log /var/log/nginx/debug.log debug; - 注意:error_log 必须放在 rewrite 所在作用域的上级(比如 rewrite 在 location 里,error_log 至少要在 server 或 http 里),否则不生效
从日志里读出关键信息
真正有用的日志行有固定模式,盯住这几个关键词:
- matches / does not match:表示某条 rewrite 正则是否命中当前请求 URI
- rewritten data:显示最终重写结果,比如 "rewritten data: /api/v2/users"
- using regex …:告诉你正在执行哪条正则(尤其多条 rewrite 时定位精准)
- test location / matched location:说明重写后是否触发了新的 location 匹配(last 标志会引发这一步)
配合辅助手段交叉验证
单看日志有时不够直观,建议组合使用:
- 加一个临时 location 输出原始变量:
location /debug-uri { return 200 "URI: $request_uri\nArgs: $args\nHost: $host"; } - 用 curl -I 或浏览器开发者工具看响应状态码和 Location 头,确认是内部跳转(无状态码变化)还是外部重定向(301/302)
- 对复杂条件(如含 $arg_ 或 $http_referer 的 if + rewrite),可用 map 提前提取并记录:
map $request_uri $ver { ~^/api/v(?\d+)/ $v; default "-"; }











