解决 Nginx 报错 rewrite internal redirection cycle 循环重定向
分析 Nginx 配置 Vue/React 单页应用路由时触发 500 rewrite or internal redirection cycle 的 try_files 陷阱与修复指南。
问题现象
用户访问前端单页应用(SPA)时,页面返回 500 Internal Server Error,Nginx error.log 中记录:
2026/11/15 13:00:00 [error] 1234#1234: *1 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 192.168.1.5, server: example.com, request: "GET /dashboard HTTP/1.1", host: "example.com"
触发根因
- 在
try_files配置指令中,回退到的最后目标文件(如/index.html)在服务器物理磁盘上根本不存在。 - Nginx 在找不到文件时尝试再次按 URL 重写匹配,连续超过 10 次内部重定向后触发死循环保护机制,强制返回 500。
解决步骤与操作命令
步骤一:核实 root 路径与 index.html 物理存在性
ls -la /var/www/html/dist/index.html
确认物理磁盘上确实存在 index.html,且 Nginx 运行用户具有读取权限。
步骤二:规范 try_files 指令配置
编辑 Nginx 站点配置:
server {
listen 80;
server_name example.com;
root /var/www/html/dist;
index index.html;
location / {
# 依次查找:真实文件 -> 真实目录 -> 回退单页入口 index.html
try_files $uri $uri/ /index.html;
}
# 针对静态资源直接返回 404,不进入 SPA 回退循环
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
}
步骤三:重载 Nginx
sudo nginx -t && sudo nginx -s reload
验证确认
使用 curl 测试路由访问:
curl -I http://example.com/dashboard
返回 HTTP/1.1 200 OK,未再发生死循环重定向,SPA 页面正常加载。


