Nginx部署SPA需正确配置root/alias与try_files:root定义路径前缀,须配合try_files实现前端路由兜底;子路径部署应优先用alias;还需配置MIME类型、Gzip压缩及合理缓存策略。

前端单页面应用(SPA)部署时,Nginx 的 root 配置不是简单指向 dist 目录本身,而是要配合 location 路径和 try_files 才能正确工作。核心原则是:root 定义的是“文件系统路径前缀”,不是最终文件位置;它必须与请求路径拼接后,恰好落到 index.html 及其他静态资源上。
root 要指向构建产物的父目录
假设 Vue/React 项目执行 npm run build 后生成的文件在 /var/www/myapp/dist/,那么:
- ✅ 正确写法:
root /var/www/myapp;+location / { try_files $uri $uri/ /dist/index.html; } - ✅ 或更常用:
root /var/www/myapp/dist;+location / { try_files $uri $uri/ /index.html; } - ❌ 错误写法:
root /var/www/myapp/dist/;+location / { index index.html; }—— 缺少 try_files,刷新任意前端路由(如 /user/123)会直接 404
子路径部署时慎用 root,优先选 alias
如果应用需部署在二级路径下(例如访问地址是 https://example.com/admin/),不要在 location /admin/ 中用 root:
- ❌ 危险:
location /admin/ { root /var/www/myapp/dist; }→ 实际查找路径变成/var/www/myapp/dist/admin/xxx,找不到资源 - ✅ 推荐:
location /admin/ { alias /var/www/myapp/dist/; }→ 请求/admin/js/app.js直接映射到/var/www/myapp/dist/js/app.js - 注意:
alias值末尾必须带斜杠,root末尾加不加斜杠不影响结果
必须搭配 try_files 实现路由兜底
SPA 的前端路由(如 /dashboard、/profile)在服务端没有真实文件,Nginx 必须把未匹配的请求内部重写为 /index.html,由前端 JS 路由接管:
立即学习“前端免费学习笔记(深入)”;
-
try_files $uri $uri/ /index.html;是标准写法 -
$uri:先查真实文件(如 logo.png、app.js) -
$uri/:再查目录(如 /static/ → 尝试找 static/index.html) -
/index.html:兜底,返回 index.html 内容,URL 不变,浏览器不跳转
别漏掉基础配套配置
只配 root 和 try_files 还不够,容易引发资源加载异常或缓存问题:
- MIME 类型:确保
include /etc/nginx/mime.types;已启用,否则 CSS/JS 可能被当作文本下载 - Gzip 压缩:
gzip on;+ 相关 gzip_* 指令,加快 HTML/JS/CSS 传输 - HTML 缓存控制:对
.html文件禁用强缓存,避免更新后用户仍看到旧版;可用add_header Cache-Control "no-cache, no-store, must-revalidate"; - 其他静态资源(js/css/img)可设长期缓存:
location ~* \.(js|css|png|jpg|gif|ico)$ { expires 1y; add_header Cache-Control "public, immutable"; }


















