要查看 nginx 的 rewrite 匹配过程,需先确认编译时含 --with-debug 支持(nginx -v | grep with-debug),再在 nginx.conf 中配置 error_log /var/log/nginx/error.log debug,重载后通过 error.log 中 "using configuration"、"rewritten data" 等关键词分析匹配与重写过程。

要查看 Nginx 的 rewrite 匹配过程,核心是开启 rewrite 调试日志,这需要启用 debug 级别的日志,并确保编译时包含 --with-debug 支持。
确认 Nginx 编译时启用了 debug 支持
运行以下命令检查是否支持 debug 日志:
nginx -V 2>&1 | grep -o with-debug
如果输出为空,说明当前 Nginx 未编译 debug 模块,无法启用 rewrite 调试日志,需重新编译或换用已带 debug 的包(如 Ubuntu/Debian 的 nginx-debug 包)。
配置 error_log 开启 debug 级别
在 nginx.conf 的 main 或 http 块中设置:
Linux系统管理专家,覆盖12大模块:用户权限、SSH、存储、网络、systemd、防火墙、日志监控、备份恢复、TLS证书、Ansible、容器、IaC。提供配置、验证、加固、监控、备份、自动化、故障排查、回滚闭环。关键词:useradd、sudo、sshd_config、chmod、SEL...
error_log /var/log/nginx/error.log debug;
⚠️ 注意:
- debug 级别日志量极大,仅用于临时调试,切勿长期开启;
- 日志路径需确保 Nginx 进程有写入权限;
- 修改后需重载: nginx -s reload(非 restart)。
定位 rewrite 相关的调试日志行
触发请求后,在 error.log 中搜索关键词:
-
"using configuration"—— 当前匹配到的 location 块 -
"rewritten data"—— rewrite 执行后的 URI 变化 -
"test location","using location"—— location 匹配过程 -
"rewrite or internal redirection cycle"—— 表示 rewrite 循环,需检查规则
例如一条典型日志:
2024/05/20 10:12:34 [debug] 12345#12345: *1 http script regex: "^/old/(.*)$" matched, new uri: "/new/$1"
辅助技巧:缩小日志范围
避免全量 debug 日志干扰,可:
- 用
grep实时过滤:tail -f /var/log/nginx/error.log | grep -E "(rewrite|location|regex)" - 为特定 server 或 location 添加独立日志(不推荐 debug 级,但可设 warn):
- 临时加
return 200 "uri: $request_uri, args: $args";验证变量值










