本文提供一套现代前端项目的部署最佳实践,涵盖 Nginx 配置、Jenkins 自动化、HTTPS 配置、快速回滚 等关键环节,帮助前端开发者快速构建稳定、高效、安全的生产环境。
目录
1. 部署环境准备
推荐环境:
- 服务器:Linux (Ubuntu/CentOS)
- 基础软件:
- Nginx (静态资源托管 / 反向代理)
- Jenkins (持续集成与部署)
- Certbot (自动申请与续签 HTTPS 证书)
2. 前端构建与目录规范
打包后的前端项目建议目录结构如下:
/var/www/your-app/
├── releases/ # 历史版本存放
│ └── 2025-08-17-xxxx/
└── current -> /var/www/your-app/releases/2025-08-17-xxxx/ # 软链,指向当前版本
👉 好处:
- 清晰的版本化管理
- 回滚方便,只需切换
current链接
3. Nginx 配置最佳实践
示例配置:
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri; # 强制跳转 HTTPS
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
# SSL 配置
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
root /var/www/your-app/current;
index index.html;
error_page 404 /index.html; # SPA 路由支持
location / {
try_files $uri /index.html;
}
# 静态资源缓存策略
location ~* .(?:ico|css|js|gif|jpe?g|png|woff2?)$ {
expires 30d;
access_log off;
add_header Cache-Control "public";
}
}
要点:
- 强制 HTTPS
- 开启 HTTP/2 提升性能
- SPA 应用支持前端路由
- 静态资源缓存 30 天
4. Jenkins 自动化部署流程
4.1 插件安装
- Git:拉取代码
- NodeJS Plugin:管理 Node 版本
- Pipeline:流水线构建
- Publish Over SSH:部署到服务器
4.2 Pipeline 脚本示例
pipeline {
agent any
environment {
NODEJS_HOME = tool name: 'node16', type: 'NodeJS'
PATH = "${NODEJS_HOME}/bin:${env.PATH}"
}
stages {
stage('Checkout') {
steps {
git branch: 'main', url: 'git@github.com:your/repo.git'
}
}
stage('Build') {
steps {
sh 'npm install'
sh 'npm run build'
}
}
stage('Deploy') {
steps {
sshPublisher(publishers: [
sshPublisherDesc(
configName: "prod-server",
transfers: [
sshTransfer(
sourceFiles: 'dist/**',
removePrefix: 'dist',
remoteDirectory: "/var/www/your-app/releases/${env.BUILD_NUMBER}",
execCommand: """
ln -sfn /var/www/your-app/releases/${env.BUILD_NUMBER} /var/www/your-app/current
systemctl reload nginx
"""
)
]
)
])
}
}
}
}
👉 特点:
- 自动上传构建产物到
/releases/{BUILD_NUMBER} - 使用软链切换版本
systemctl reload nginx实现无缝切换
5. HTTPS 证书自动化
申请与配置证书:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com
自动续签:
sudo systemctl enable certbot.timer
6. 回滚方案
若新版本出现问题,只需执行:
ln -sfn /var/www/your-app/releases/上一个版本号 /var/www/your-app/current
systemctl reload nginx
👉 零停机回滚,保证线上稳定性。
7. 总结
- 目录清晰:版本化管理,软链切换
- Nginx 配置合理:HTTPS、缓存、SPA 支持
- Jenkins 自动化:Checkout → Build → Deploy → Reload
- 证书自动化:Certbot 自动续签
- 回滚快速:一键切换版本
🚀 通过以上实践,你的前端项目将具备:
- 自动化构建与部署
- 高性能与安全传输
- 稳定可回滚的上线机制
这就是现代前端部署的最佳实践。