DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Vite 报错 Assets relative path 404 base 配置失效修复

排查 Vite 打包部署到服务器非根子路径(如 /app/)后,所有图片、字体与 CSS 资源报 404 Not Found,分析 base 配置选项与生产静态资源定位。

问题现象

将 Vite 打包生成的 dist 目录上传至服务器的 https://example.com/portal/ 访问,页面空白,网络面板所有 JS/CSS 均返回 404:

GET https://example.com/assets/index.js 404 (Not Found)
GET https://example.com/assets/style.css 404 (Not Found)

触发根因

  1. Vite 默认的构建基准公共路径(base)为绝对根路径 '/';
  2. 当网站托管在虚拟子目录(/portal/)或通过相对路径访问时,浏览器自动向网站顶级根目录发起资源寻址;
  3. 未针对特定子目录进行编译时基准路径重设。

解决步骤

在 vite.config.ts 中明确设置 base 路径或使用相对基准路径

编辑配置:

import { defineConfig } from 'vite';

export default defineConfig({
  // 若子目录固定配置为 '/portal/';若希望任意子路径均兼容配置为 './'
  base: './',
  build: {
    assetsDir: 'static',
  },
});

确保服务端反向代理正确处理了客户端路由 fallback

在 Nginx 中配置:

location /portal/ {
    alias /var/www/portal/dist/;
    try_files $uri $uri/ /portal/index.html;
}

验证确认

重新打包部署:

资源路径自动生成为相对路径或精准指向 /portal/static/...,页面秒级完整渲染呈现。