将 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 等) 和 错误日志,进一步分析!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论