Skip to content

Nginx 与 Vite Vue Public 路径冲突极简解决方案

上次更新 2025年9月7日星期日 4:44:2 字数 0 字 时长 0 分钟

1. 核心问题

Nginx 的 location 路径与 Vite Vue 项目 public 目录第一层子目录同名时,Nginx 优先匹配 location 规则,导致 public 下静态资源报 404

2. 问题本质

  1. Vite 机制public 目录文件原样复制到 dist 根目录,需用绝对路径(如 /static/img/logo.png)访问。

  2. Nginx 优先级location 前缀匹配(如 /static/)优先级高于 SPA 路由的 try_files 逻辑,拦截了静态资源请求。

3. 解决方案(优先级排序)

方案 1:修改项目目录(推荐)

核心:重命名 public 下冲突目录,从根源避免冲突。

  1. public/static/ 改为 public/assets/(或其他名称)。

  2. 代码中资源引用从 /static/xxx 改为 /assets/xxx

  3. 重新 npm run build 部署。

方案 2:Vite 配置基础路径

核心:给资源加前缀,避开冲突路径。

  1. 修改 vite.config.js
export default defineConfig({

 base: '/app/' // 加前缀 /app/

})
  1. 资源引用改为 /app/static/xxx

  2. Nginx 适配

location /app/ {

   try\_files \$uri \$uri/ /app/index.html;

}

4. 验证步骤

  1. 执行 nginx -t 检查配置,systemctl restart nginx 重启。

  2. 直接访问资源路径(如 http://example.com/static/img/logo.png),确认返回 200。

  3. 访问项目,检查控制台无 404。

5. 关键排查

问题现象核心原因解决办法
改配置后仍 404Nginx 未重启 / 语法错误执行 nginx -t 并重启
静态资源不匹配location 优先级错误确保静态资源规则用 ^~ 前缀
路径异常Vite base 与 Nginx 不匹配统一 base 配置与 Nginx 访问路径
关注公众号