Vue3项目部署需先构建再配Nginx:①执行npm run build生成dist目录;②将dist文件复制到Nginx根目录(如/usr/share/nginx/html);③配置Nginx的try_files $uri $uri/ /index.html解决history路由404;④对/assets/启用immutable缓存,/index.html禁用强缓存。

Vue 3 项目初始化阶段不涉及 Nginx 配置,Nginx 是部署时才介入的服务器组件。真正要做的,是在项目构建完成、生成 dist 目录后,再配置 Nginx 去服务这些静态文件。关键在于“先构建,再配 Nginx”,而不是在项目初始化时就动 Nginx。
1. 先完成 Vue 3 项目的生产构建
确保项目已按生产环境准备就绪:
- 确认路由模式:若用 history 模式(URL 如
/home),Nginx 必须加try_files防 404;若用 hash 模式(/#/home),Nginx 可直接托管,无需特殊配置 - 执行构建命令:
npm run build(Vite)或vue-cli-service build(Vue CLI) - 检查输出目录:
dist/下必须有index.html和assets/,且所有资源路径正确(可通过npx serve dist本地验证)
2. Nginx 基础服务配置(单页应用必需)
将 dist 内容复制到 Nginx 根目录(如 /usr/share/nginx/html),然后编辑站点配置文件(如 /etc/nginx/conf.d/vue-app.conf):
将静态 Vue 页面(index.vue)改造为动态页面(Custom.vue);稿源仅限 index.vue、其引用的 CSS 与资源路径,禁止参考仓库内其他文件。Invoke when user wants to transform a static Vue page into a dynamic data-driven page with Element UI components.
-
监听与根路径:
listen 80;+root /usr/share/nginx/html;+index index.html; -
解决 history 路由刷新 404:在
location /块中添加try_files $uri $uri/ /index.html; -
禁止入口文件强缓存:单独匹配
location = /index.html并设add_header Cache-Control "no-cache";,确保发版后用户能立刻看到新页面
3. 补充生产级优化项(非必需但推荐)
这些配置提升性能和稳定性,可在基础配置上叠加:
立即学习“前端免费学习笔记(深入)”;
-
静态资源长期缓存:对
/assets/下带 hash 的文件启用 immutable 缓存,如add_header Cache-Control "public, max-age=31536000, immutable"; -
Gzip 压缩:开启
gzip_static on;(需提前用vite-plugin-compression或构建脚本生成.gz文件) -
API 代理(如有后端):用
location /api/ { proxy_pass http://backend-server; },注意proxy_pass末尾不加路径,避免重复拼接
4. 子路径部署(如 /admin/)需同步改项目配置
如果希望项目运行在 https://example.com/admin/,不能只靠 Nginx 配置,还必须在前端项目里对齐:
- Vite 项目:在
vite.config.ts中设置base: '/admin/' - Vue Router:使用
createWebHistory('/admin/') - Nginx 配置对应 location:
location /admin/ { alias /usr/share/nginx/html/admin/; try_files $uri $uri/ /admin/index.html; }(注意用alias而非root)

















