Vue、React打包的dist目录天然适配Nginx的root配置,因其URL路径与磁盘结构完全一致;location / { root /path/dist; index index.html; try_files $uri $uri/ /index.html; }可正确处理SPA路由和静态资源,而alias易导致路径错乱,仅适用于子路径映射等特殊场景。

直接用 root,别绕弯。Vue、React 打包出来的 dist 目录,就是整个站点的根,天然匹配 root 的行为逻辑。
什么时候该用 root
前端构建产物(如 dist)本身就是一个完整可运行的静态网站,访问 / 就该加载 index.html,访问 /js/app.js 就该加载对应资源 —— 这种“URL 路径和磁盘目录结构完全一致”的情况,root 是最自然、最安全的选择。
-
location / { root /var/www/my-app/dist; index index.html; }:请求
/→ 找/var/www/my-app/dist/index.html -
location /assets/ { root /var/www/my-app/dist; }:请求
/assets/logo.png→ 找/var/www/my-app/dist/assets/logo.png - root 值末尾写不写
/都行,Nginx 会自动补全,但统一写成/var/www/my-app/dist/更清晰
alias 不适合整站托管,容易出错
alias 的设计初衷是“路径前缀替换”,不是“挂载站点”。如果硬用 alias 托管 dist:
- location / { alias /var/www/my-app/dist/; } → Nginx 报错:location / 不能跟 alias(语法不允许)
-
location /app/ { alias /var/www/my-app/dist/; } → 请求
/app/确实能加载 index.html,但所有相对路径(如./css/main.css)在浏览器里仍按/app/css/解析,而实际资源在/css/,404 风险高 - alias 值末尾漏掉
/,比如写成alias /var/www/my-app/dist;,就会拼出/var/www/my-app/distindex.html,直接崩
特殊场景才考虑 alias
只有当你需要把某个 URL 路径“映射到一个名字不匹配的磁盘目录”时,alias 才真正有用:
- 挂载 Swagger UI:
location /api/docs/ { alias /opt/swagger-ui/; }(URL 有/api/docs/,但磁盘里没有这层目录) - 共享图标库:
location /icons/ { alias /mnt/shared-icons/; }(避免把图标混进主项目 dist) - 子应用独立部署:
location /admin/ { alias /srv/my-admin/; }(主站用 root,后台用 alias 挂载不同物理路径)
配置示例:标准前端部署
假设打包产物放在 /opt/web/dist,想通过 https://example.com/ 访问:
server {
listen 80;
server_name example.com;
charset utf-8;
<pre class="brush:php;toolbar:false;">location / {
root /opt/web/dist;
index index.html;
# 支持前端路由(如 Vue Router history 模式)
try_files $uri $uri/ /index.html;
}
# 静态资源缓存优化(可选)
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}}
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











