将 Vue 项目部署到线上后出现 404 错误,通常是由于 路由配置、服务器设置或资源路径问题 导致的。以下是常见原因及解决方案:
1. 前端路由(history 模式)未配置服务器支持
问题原因
-
Vue 默认使用 hash 模式(URL 带
#
),但若使用 history 模式(无#
的 URL),刷新页面时服务器会尝试匹配该路径,但实际不存在对应的文件,导致 404。 -
示例:
访问https://example.com/user/123
,服务器会查找/user/123/index.html
,但 Vue 是单页应用(SPA),所有路由应由前端处理。
解决方案
-
方案 1:配置服务器重定向到
index.html
确保所有请求都返回index.html
,由 Vue Router 接管路由。 - Nginx 配置:
location / { try_files $uri $uri/ /index.html; }
- Apache 配置(
.htaccess
):RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
-
Netlify/Vercel:
在部署设置中指定rewrites
规则,指向index.html
。 - 方案 2:改用 hash 模式
在 Vue Router 中强制使用 hash 模式:
const router = new VueRouter({
mode: 'hash', // 默认是 'history'
routes: [...]
});
2. 静态资源路径错误(JS/CSS 404)
问题原因
-
打包后的资源路径错误,浏览器无法加载 JS/CSS 文件。
-
常见于项目部署在子目录(如
https://example.com/subdir/
),但静态资源引用的是绝对路径。
解决方案
-
修改
vue.config.js
,设置正确的publicPath
:module.exports = { publicPath: process.env.NODE_ENV === 'production' ? '/your-subdir/' : '/' };
-
-
如果部署在根目录,用
publicPath: '/'
; -
如果部署在子目录(如
/subdir/
),用publicPath: '/subdir/'
。
-
-
检查打包后的
index.html
确保引用的 JS/CSS 路径正确,例如:<script src="/subdir/js/app.123456.js"></script>
3. 服务器未正确配置 MIME 类型
问题原因
-
服务器未正确返回
.js
、.css
等文件的 MIME 类型,导致浏览器拒绝加载。
解决方案
Nginx 配置:
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public";
try_files $uri =404;
}
Apache 配置:确保 .htaccess
包含:
AddType application/javascript js
AddType text/css css
4. 部署目录结构错误
问题原因
-
打包后的
dist
文件夹内容未完整上传到服务器。 -
服务器根目录未指向
dist
文件夹。
解决方案
-
确保上传的是
dist
内的所有文件(而非dist
文件夹本身)。 -
检查服务器配置的根目录是否正确:
server { root /path/to/your/dist; index index.html; }
5. 浏览器缓存问题
问题原因
-
旧版本缓存导致加载异常。
解决方案
-
强制刷新页面(
Ctrl + F5
或Cmd + Shift + R
)。 -
在文件名中添加哈希(Vue CLI 默认已配置):
// vue.config.js module.exports = { filenameHashing: true // 默认开启 };
总结排查步骤
-
检查服务器路由配置(History 模式需重定向到
index.html
)。 -
验证静态资源路径(
publicPath
是否正确)。 -
查看浏览器控制台(Network 面板确认哪些文件返回 404)。
-
检查服务器日志(如 Nginx 的
error.log
)。 -
清除缓存或使用无痕模式 测试。
如果问题仍未解决,可以提供具体的 部署环境(Nginx/Apache/Netlify 等) 和 错误日志,进一步分析!