Nginx托管前端项目时,root必须精准指向index.html所在物理目录(如/opt/dist),而非上级目录或URL路径;需配合publicPath和location使用,并添加try_files $uri $uri/ /index.html;防止SPA刷新404。

托管前端项目时,Nginx 的 root 指令必须精准指向打包后 index.html 所在的**物理目录**,而不是它的上级目录,也不是 URL 路径。配错会导致白屏、静态资源 404 或刷新路由 404。
root 指向的是文件系统路径,不是 URL 前缀
root 定义的是 Nginx 查找文件的起点目录,它会把请求的 URI(比如 /js/app.js)直接拼在 root 路径后面,形成真实文件路径。
- 若 Vue 打包输出到
/opt/dist,且index.html就在该目录下,那么 root 必须设为/opt/dist - 配置
root /opt;是错的——Nginx 不会自动进入dist子目录,访问/时会去找/opt/index.html,而它不存在 - 配置
root /opt/dist/;和root /opt/dist;效果一致,末尾斜杠不影响查找,但语义更清晰
root 要和 publicPath、location 协同匹配
Vue CLI 构建时通过 vue.config.js 中的 publicPath 控制所有资源引用前缀,这个值必须和 Nginx 的 root + location 规则对得上。
- 部署在域名根路径(如
https://example.com/):设publicPath: '/',Nginx 配置为
root /opt/dist;
try_files $uri $uri/ /index.html;
}
- 部署在子路径(如
https://example.com/admin/):必须设publicPath: '/admin/',此时推荐用alias,因为root在子路径下容易出错
alias /opt/dist/;
try_files $uri $uri/ /admin/index.html;
}
注意:alias 结尾必须带 /,否则路径拼接会错位;root 不适合混用于带路径的 location 场景。
立即学习“前端免费学习笔记(深入)”;
SPA 项目必须加 try_files 防 404
单页应用(Vue/React)靠前端路由跳转,但刷新页面时浏览器会向服务端发真实请求。Nginx 默认找不到 /user/profile 这类路径,直接返回 404。
- 加上
try_files $uri $uri/ /index.html;后,Nginx 会先尝试找真实文件,找不到就回退到/index.html,由前端路由接管 - 这行必须放在
location块里,且不能遗漏$uri/(处理目录访问) - 不要写成
try_files /index.html;—— 缺少前置检查,会导致所有请求都返回 index.html,连 404 都没了
优先级与作用范围要理清
root 可以出现在 http、server、location 块中,生效范围按就近原则:
-
location内的 root 优先级最高,只对该路径生效 -
server块里的 root 是默认根路径,适合多数静态站点 -
http块设 root 很少用,易被覆盖,不推荐 - 同一个 server 下多个 location,建议统一用 server 级 root,特殊路径再单独用 location + root 或 alias


















