# 11.5 前端部署 :::tip 概述 前端构建为静态产物(dist/),生产由 Nginx 托管:静态文件 + SPA 路由回退 + /api 与 /upload 反代后端。支持根路径与子路径两种部署。 ::: ## 构建 ```sh cd ui pnpm install --frozen-lockfile pnpm build # production 模式 # 产物:ui/dist/ ``` 多环境构建:`pnpm build:test / build:uat / build:prod`(对应 .env.* 文件)。 ## Nginx 配置(根路径) ```nginx server { listen 80; server_name example.com; root /opt/easygoadmin/ui/dist; index index.html; # gzip gzip on; gzip_types text/css application/javascript application/json image/svg+xml; # SPA 路由回退 location / { try_files $uri $uri/ /index.html; } # 接口反代 location /api/ { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_read_timeout 60s; client_max_body_size 20m; # 对齐 file.maxSize(含表单 multipart) } # 上传静态文件(或直挂文件服务/CDN) location /upload/ { proxy_pass http://127.0.0.1:8000; } # API 文档(可选:收紧为内网/Basic Auth) location /swagger { proxy_pass http://127.0.0.1:8000; } location /api.json { proxy_pass http://127.0.0.1:8000; } # 静态资源缓存(带 hash 的资源长缓存) location /assets/ { expires 30d; add_header Cache-Control "public, immutable"; } } ``` ## 子路径部署 ```text 1. 构建:.env 配 VITE_PUBLIC_PATH=/admin/(部署公网路径) 2. Nginx: location /admin/ { alias /opt/dist/; try_files $uri $uri/ /admin/index.html; } 3. 接口仍走 /api(baseURL 与后端一致)——注意 Nginx location 匹配 ``` ## HTTPS ```text HTTPS 由前置代理/Nginx 终止: listen 443 ssl http2; ssl_certificate /etc/ssl/example.pem; ssl_certificate_key /etc/ssl/example.key; # HTTP → HTTPS 重定向 后端服务本身 HTTP 内网(:8000 不对外) ``` ## 部署验证 ```text □ 首页加载(无白屏) □ 登录 → 首页菜单/仪表盘正常 □ 刷新子路由不 404(SPA 回退生效) □ 接口经 /api 反代正常(Network 面板核对) □ 上传/图片预览正常(/upload 反代或 CDN) □ 403/401 页面(exception/403)可达 □ 构建资源长缓存生效(二次访问 assets 命中缓存) ``` ## 发布流程 ```text 1. pnpm build(CI 或本地) 2. dist 上传服务器(rsync/scp,保留旧版本目录) 3. Nginx root 切换或软链切换(原子切换) 4. 验证 → 出错回滚软链 index.html 不缓存(no-cache),静态 assets 长缓存——发布即生效 ``` ## 常见问题 | 症状 | 排查 | |------|------| | 刷新 404 | try_files 回退缺失或子路径 /admin/index.html 写错 | | 接口 404/502 | /api 反代地址/端口;后端未启动 | | 跨域报错 | 应为同域反代——检查是否前端直连了后端地址 | | 上传失败(413) | Nginx client_max_body_size 小于 file.maxSize | | 登录后回登录页 | access_token 读取/存储;后端 401(令牌/时钟) | | 老页面缓存 | index.html 被缓存——加 no-cache 头 |