部署到子目录后,路由和图片全错位
项目挂到 /gis/ 下,首页能打开,但图标、瓦片、接口全部请求到了根路径。
现象
页面加载后,静态资源与接口请求都带着错误的前缀:
GET https://example.cn/icons/poi.png 404 (Not Found)
GET https://example.cn/api/layers 404 (Not Found)
# 实际部署位置是 https://example.cn/gis/
路由跳转到 /map 时,页面直接 404,因为服务器上没有这个路径。
原因
构建工具的 base 默认是 /,生成的资源地址以根路径开头。
路由的 history 模式也默认按根路径匹配。
代码里写的 fetch('/api/layers') 同样按根路径解析。
这三处任意一处没改,都会 404。
排查过程
- 看构建后的
index.html,资源地址是否以/gis/开头。 - 在浏览器里读
location.pathname,确认实际部署前缀。 - 搜索代码中所有以
'/'开头的接口与图片地址。
console.log(location.pathname); // /gis/index.html
console.log(import.meta.env.BASE_URL); // / ← 未配置时为根路径
解决方案
构建配置里写死基路径,或者用环境变量区分部署环境:
// vite.config.js
export default defineConfig(function () {
return {
base: process.env.DEPLOY_BASE || '/gis/'
};
});
路由同步设置 base,否则刷新后会落到错误路径:
var router = new VueRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: routes
});
代码里的资源与接口不要写死根路径。用构建变量或相对路径统一处理:
var BASE = import.meta.env.BASE_URL;
var layerUrl = BASE + 'data/layers.json';
var iconUrl = BASE + 'icons/poi.png';
fetch(BASE + 'api/layers') // 或由请求库统一配置 baseURL
.then(function (r) { return r.json(); });
Nginx 侧把子路径转发到静态目录,并处理 history 回退:
location /gis/ {
alias /var/www/gis/dist/;
try_files $uri $uri/ /gis/index.html;
}
location /gis/api/ {
proxy_pass http://127.0.0.1:8080/api/;
proxy_set_header Host $host;
}
验证
index.html 中所有资源以 /gis/ 开头。
直接访问 /gis/map 能正常打开页面,不 404。
图标、瓦片、接口请求的前缀与部署目录一致。
在根路径访问时给出明确 404,而不是空白页。
三处一起改:构建 base、路由 base、请求 baseURL。
只改其中一处,问题会从“资源 404”变成“接口 404”,看起来像新问题。
经纬志(2026)。《部署到子目录后,路由和图片全错位》。https://www.jingweizhi.com/cookbook/base-path-wrong.html(访问日期 2026-11-03)。