Vue项目如何进行部署?是否有遇到部署服务器后刷新404问题?
参考答案
部署流程
npm run build # 产出 dist/
# 上传 dist 到 Nginx / OSS+CDN / 静态托管
Nginx 示例(history 模式):
server {
listen 80;
root /var/www/app/dist;
location / {
try_files $uri $uri/ /index.html; # 关键:未命中的路径回落到 index.html
}
location /api/ {
proxy_pass http://backend:8080; # 接口反向代理,顺便解决跨域
}
location ~* \.(js|css|png|jpg|svg|woff2)$ {
expires 1y; # 静态资源长缓存(文件名带 hash)
add_header Cache-Control "public, immutable";
}
location = /index.html {
add_header Cache-Control "no-cache"; # 入口文件不缓存,保证发版生效
}
}
刷新 404 的原因与解决
- 原因:history 模式下前端路由用
pushState改 URL,服务端并没有/user/123这个真实文件/目录,直接请求该 URL 就 404。 - 解决:服务端把未命中的路径 **rewrite/fallback 到
index.html**,由前端路由接管: - Nginx:
try_files $uri $uri/ /index.html; - Apache:
.htaccess里RewriteRule . /index.html [L] - 静态托管(GitHub Pages/OSS):不支持 rewrite 时改用 hash 模式 或预渲染/静态化
- Node(Express):
app.get('*', (req,res) => res.sendFile(index))(注意排除/api)
其他部署要点
- **
publicPath/base**:部署在子路径(/app/)时要配置,否则资源 404; - 环境变量:
.env.production,构建时注入(Vite 用VITE_*,vue-cli 用VUE_APP_*),不要打包进敏感密钥; - 缓存策略:入口 HTML 不缓存、资源长缓存 + hash 文件名;
- 发版一致性:灰度/蓝绿发布,避免旧 HTML + 新 JS 混用导致 chunk 加载失败(
router.onError里可提示刷新); - CI/CD:构建产物 + 版本号 + 回滚能力;
- 压缩:gzip/brotli、HTTP/2、CDN 加速;
- 监控:健康检查、错误上报、性能埋点。