最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Nginx 中故障排查如何通过日志排查伪静态重写规则陷入死循环
时间:2026-08-29 11:14:48 编辑:袖梨 来源:一聚教程网
直接查 error.log 中“rewrite or internal redirection cycle”及“internally redirecting to”行定位循环终点,再结合 access.log 高频记录和 debug 日志的 rewrite 跳转链,可确认伪静态规则是否真形成闭环,并重点排查无保护 rewrite、try_files 与 rewrite 冲突等高危配置。
直接查 error.log 里的关键错误行,再结合 access.log 和 debug 日志还原重写路径,就能快速确认是不是伪静态规则真在循环。
看 error.log 是否出现明确循环报错
打开 /var/log/nginx/error.log,搜索以下两行:
- rewrite or internal redirection cycle —— 这是 Nginx 主动截断后的明确信号,说明已触发内部重写保护(默认最多 10 次)
-
internally redirecting to "/xxx" —— 紧跟在上一行之后,显示最终卡住的 URI,比如
/index.php或/app/,这就是循环终点
如果这两行反复出现,基本可判定是 rewrite 规则自身逻辑闭环导致,不是后端或权限问题。
用 access.log 验证请求是否高频重复
伪静态死循环会在 access.log 中留下“指数级刷屏”痕迹:
- 同一 IP 对同一路径(如
/user/123)在几秒内出现几十甚至上百条记录 - 状态码集中为 301/302(用了 redirect/permanent)或 500(用了 last 导致内部跳转超限)
- 响应体大小几乎一致,且时间戳高度密集(例如每行相差不到 0.1 秒)
执行命令快速筛查:
awk '$9 ~ /^(301|302|500)$/ {print $1, $7, $9, $13}' /var/log/nginx/access.log | tail -20
其中 $13 是 $upstream_http_location,能帮你看到后端返回的跳转地址是否也在打转。
开启 debug 日志看清每一步 rewrite 跳转
error.log 只报结果,debug 日志才报过程。临时启用:
- 确认 Nginx 编译时含
--with-debug(运行nginx -V 2>&1 | grep -o with-debug) - 在 http 块中加:error_log /var/log/nginx/rewrite-debug.log debug;
- 重启 Nginx,复现请求,然后实时过滤:
tail -f /var/log/nginx/rewrite-debug.log | grep -E "(rewrite|redirect|phase|location)"
你会看到类似:
*123456 rewrite phase: 3, "/user/123" → "/index.php?path=user/123"
*123456 test location: "/index.php"
*123456 matched location: /
这说明 rewrite 后又回到了 location /,而该块里很可能还有另一条 rewrite ^/.*$ /index.php last; —— 循环就在这里形成。
重点检查伪静态常用高危写法
以下配置在伪静态场景中极易引发循环,需逐条核对:
-
无条件 rewrite + last:如
rewrite ^/(.*)$ /index.php?path=$1 last;放在location /里,而/index.php本身又匹配该 location -
try_files 与 rewrite 混用:如
try_files $uri $uri/ /index.php;后面又跟了rewrite ^/api/(.*)$ /index.php?r=api/$1 last;,两者都可能把请求导向/index.php -
location 使用前缀匹配但范围过宽:如
location /或location ^~ /包裹 rewrite,导致 rewrite 后的新 URI(如/index.php)仍落入同一块 -
if 块中嵌套 rewrite 且判断不严谨:如
if (!-f $request_filename) { rewrite ^(.*)$ /index.php last; },但/index.php文件存在,却因权限或路径问题实际无法访问,Nginx 误判为 “not found” 再次触发