index指令应精简为单文件配置(如index index.html),root路径需严格对齐且末尾无斜杠,必须配合try_files $uri $uri/ /index.html实现spa路由兼容。

前后端分离场景下,index 指令本身不需要复杂配置,关键是“够用、准确、不干扰”。它只负责处理以 / 或 /xxx/ 结尾的目录型请求,而绝大多数前端路由(如 /user、/login)根本不会触发它。所以精简的核心是:删冗余、守位置、配兜底。
只在 server 块里写一行 index
避免放在 http 全局块或 location 外层;每个站点独立定义,防止多站点冲突:
-
✅ 推荐:
index index.html;—— 单文件最安全,语义清晰,无顺序歧义 -
❌ 避免:
index index.html index.htm default.html;—— 多文件增加权限/存在性检查开销,且实际项目中极少需要 fallback 到 .htm - 若项目明确不用 HTML 入口(如纯 SPA + 后端渲染兜底),可直接省略该指令,靠
try_files主导
root 路径必须与 index 文件严格对齐
确保 root 指向的是静态资源根目录,且末尾不带斜杠;index.html 必须真实存在于该路径下,名称全小写(Linux 区分大小写):
-
✅ 正确示例:
root /www/wwwroot/myapp/dist;→ Nginx 查找/www/wwwroot/myapp/dist/index.html -
❌ 常见错误:
root /www/wwwroot/myapp/dist/;(末尾斜杠)→ 可能拼出双斜杠路径,导致 403 - 部署后手动确认:
ls -l /www/wwwroot/myapp/dist/index.html,权限建议为-rw-r--r--(644)
必须搭配 try_files 实现“裸路径”兼容
index 对 example.com(无尾斜杠)完全无效;刷新 history 路由页面时,Nginx 需靠 try_files 把所有非静态请求导向 index.html:
-
最小必要配置:
try_files $uri $uri/ /index.html; - 这行必须放在
location /块内,且紧随root和index之后 - 不要写成
try_files $uri /index.html;—— 缺少$uri/会导致目录请求(如/assets/)被错误重写,可能漏掉子目录索引
子路径首页按需单独定义,不滥用 index
如果管理后台 /admin/ 需要加载 admin.html,不要改全局 index,而是用独立 location:
location /admin/ { root /www/wwwroot/myapp/dist; index admin.html; }- 此时实际查找路径是
/www/wwwroot/myapp/dist/admin/admin.html(root + URI + index 文件) - 仍建议该 location 内也加
try_files $uri $uri/ /admin.html;,保持行为一致











