vue部署到线上为啥会出现404的原因分析及解决

将 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 + F5Cmd + Shift + R)。
  • 在文件名中添加哈希(Vue CLI 默认已配置):
// vue.config.js
module.exports = {
  filenameHashing: true // 默认开启
};

总结排查步骤

  • 检查服务器路由配置(History 模式需重定向到 index.html)。
  • 验证静态资源路径publicPath 是否正确)。
  • 查看浏览器控制台(Network 面板确认哪些文件返回 404)。
  • 检查服务器日志(如 Nginx 的 error.log)。
  • 清除缓存或使用无痕模式 测试。

如果问题仍未解决,可以提供具体的 部署环境(Nginx/Apache/Netlify 等)错误日志,进一步分析!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

来源链接:https://www.jb51.net/javascript/339807k0s.htm

© 版权声明
THE END
支持一下吧
点赞14 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容