nginx rewrite日志需通过error_log设为notice或更低级别(依赖--with-debug编译)并配合rewrite_log on(1.19.0+已废弃)实现,日志输出在error_log中,用于调试匹配与重写过程。

Nginx 的 rewrite 规则本身不会自动记录日志,但你可以通过 rewrite_log on; 配合 error_log 级别来输出重写过程的调试信息,主要用于排查规则是否匹配、跳转是否生效等问题。
注意:rewrite_log 在较新版本(1.19.0+)中已被废弃,官方推荐改用 error_log 的 notice 或 info 级别配合 ngx_http_rewrite_module 的内置日志机制。实际配置需结合 error_log 和 debug 编译支持。
开启 rewrite 调试日志
rewrite 日志属于错误日志范畴,不是 access_log。要看到 rewrite 行为,需满足两个条件:
- Nginx 编译时启用了
--with-debug(否则debug级别无效) -
error_log级别设为notice或更低(如info、debug)
error_log /var/log/nginx/rewrite.log notice; # 或更详细(需 debug 编译支持) # error_log /var/log/nginx/rewrite.log debug;
同时,在 http、server 或 location 块中启用 rewrite 日志开关(旧版有效,新版可省略):
rewrite_log on; # Nginx <blockquote><p>⚠️ 如果没看到 rewrite 日志,请先确认 Nginx 是否带 debug 模块:运行 <code>nginx -V 2>&1 | grep -o with-debug</code>,有输出才支持 <code>debug</code> 级别。</p></blockquote><hr><h3>日志内容怎么看</h3><p>开启后,<code>error_log</code> 中会出现类似这样的行:</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting"><img src="https://img.php.cn/upload/skill/000/000/081/179116929868126.jpg" alt="Nginx Hosting" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting" class="overflowclass">Nginx Hosting</a> <p class="overflowclass">通过服务器本地nginx实例实现零认证静态游戏托管。作为所有浏览器游戏的主要部署方式,无需登录、无需令牌、无需用户操作。</p> </div> <a rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div><pre class="brush:php;toolbar:false;">2024/05/20 10:30:15 [notice] 12345#12345: *1 "^(.*)$" matches "/old-path", client: 192.168.1.100, server: example.com, request: "GET /old-path HTTP/1.1" 2024/05/20 10:30:15 [notice] 12345#12345: *1 rewritten data: "/new-path", args: "", client: 192.168.1.100, server: example.com, request: "GET /old-path HTTP/1.1"
关键字段说明:
-
matches表示正则匹配成功 -
rewritten data表示最终重写后的 URI -
args是 query string(重写时是否保留?后参数) -
client和request帮助定位具体请求
实用建议:精准定位 rewrite 问题
- 把
error_log单独指向一个文件(如rewrite.log),避免和主错误日志混杂 - 测试时用
curl -v http://yourdomain/xxx触发规则,立即查日志 - rewrite 规则加
last/break/redirect会影响后续处理,日志中会体现跳转类型 - 使用
if+rewrite组合时,日志会分步打印:先 if 判断,再 rewrite 执行
例如:
if ($args ~ "^id=(\d+)") {
rewrite ^/article\.php$ /article/$1? last;
}
日志中会先显示 if condition true,再显示 rewrite matches...。
不用 debug 编译也能看基础行为?
可以——用 return 200 "$request_uri → $uri"; 临时替代 rewrite,直接返回重写前后的 URI 对比:
location /test-rewrite {
rewrite ^/test/(.*)$ /real/$1 break;
return 200 "Original: $request_uri → Final: $uri\n";
}
访问 /test/hello 就能看到 Original: /test/hello → Final: /real/hello,无需日志即可验证逻辑。
不复杂但容易忽略细节。










