用 Nginx 的 alias 指令部署多个前端 SPA,需为每个应用配置带结尾斜杠的 location 块,用 alias 精准映射路径,并配合 try_files $uri $uri/ /xxx/index.html 实现路由兜底;根路径应避免直接 alias /,推荐统一使用带前缀路径。

用 Nginx 的 alias 指令部署多个前端单页应用(SPA),核心在于为每个应用分配独立路径,同时确保 SPA 的路由能被正确捕获并回退到 index.html。关键不是用 root,而是用 alias 精准映射 URI 到物理目录,并配合 try_files 处理前端路由。
明确 alias 与 root 的根本区别
alias 是把 location 匹配的路径“替换”为指定目录,而 root 是在路径末尾“拼接”。例如:
-
location /admin/ { alias /var/www/admin/; }→ 请求/admin/js/app.js对应文件是/var/www/admin/js/app.js -
location /admin/ { root /var/www; }→ 同样请求会找/var/www/admin/js/app.js(多了一层admin)
部署多个 SPA 时,alias 更直观可控,避免路径嵌套出错。
为每个 SPA 配置独立 location 块
每个应用使用带结尾斜杠的 location(如 /app1/),并用 alias 指向其构建输出目录。务必注意斜杠位置——location 和 alias 值的斜杠必须严格匹配,否则文件 404。
location /app1/ { alias /opt/dist/app1/; try_files $uri $uri/ /app1/index.html; }location /app2/ { alias /opt/dist/app2/; try_files $uri $uri/ /app2/index.html; }location /dashboard/ { alias /opt/dist/dashboard/; try_files $uri $uri/ /dashboard/index.html; }
其中 try_files $uri $uri/ /xxx/index.html 是 SPA 路由兜底的关键:先找真实文件,再找目录,最后都失败就返回对应应用的 index.html,交由前端路由处理。
处理根路径冲突与默认首页
如果某个 SPA 需要托管在根路径(/),不能直接用 alias /,否则会覆盖其他配置。推荐方案是:
- 将根应用单独放在一个 server 块中,或
- 用
location = / { alias /opt/dist/main/index.html; }+location / { try_files $uri $uri/ /index.html; }组合(此时需配合root) - 更稳妥的做法:所有 SPA 都走带前缀的路径(如
/app1/,/app2/),统一风格,避免根路径特殊逻辑
另外,确保各应用构建时设置了正确的 publicPath(Vue CLI 的 baseUrl、Vite 的 base),比如设为 /app1/,否则资源请求路径会错误。
常见陷阱与验证要点
配置完别急着 reload,逐项检查:
- 检查 Nginx 错误日志:
tail -f /var/log/nginx/error.log,看是否有directory index of ... is forbidden或no such file or directory - 确认文件权限:Nginx 工作用户(如
www-data或nginx)对目标目录有读取权限 - 手动测试静态资源:访问
https://example.com/app1/static/js/main.abc123.js,看是否返回 200 - 测试前端路由:访问
https://example.com/app1/user/123,应返回app1/index.html而非 404 - 注意浏览器缓存:首次部署后清空缓存或用无痕窗口测试,避免旧
index.html缓存干扰
不复杂但容易忽略。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










