# 本地开发环境
npm run build # 生成 dist 静态文件
# 服务器环境准备
# 需要安装:Nginx、Node.js(可选,如需服务端渲染)
ssh root@你的服务器IP
# Ubuntu/Debian
sudo apt update
sudo apt install nginx -y
# CentOS
sudo yum install nginx -y
# Ubuntu 使用 ufw
sudo ufw allow 'Nginx Full'
sudo ufw allow ssh
sudo ufw enable
# CentOS 使用 firewalld
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
# 本地终端执行
scp -r dist/* root@服务器IP:/var/www/vue-project
# 如果服务器没有目录,先创建
ssh root@服务器IP "mkdir -p /var/www/vue-project"
# 1. 服务器安装 Git
sudo apt install git -y
# 2. 克隆项目
cd /var/www
git clone 你的仓库地址 vue-project
cd vue-project
npm install
npm run build
sudo vim /etc/nginx/sites-available/vue-project
server {
listen 80;
server_name 你的域名或IP;
# Vue 项目目录
root /var/www/vue-project/dist;
index index.html;
# 启用 gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 处理 Vue Router 的 history 模式
location / {
try_files $uri $uri/ /index.html;
}
# 缓存静态资源
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
# 创建符号链接
sudo ln -s /etc/nginx/sites-available/vue-project /etc/nginx/sites-enabled/
# 测试配置
sudo nginx -t
# 重启 Nginx
sudo systemctl restart nginx
# 安装 Certbot
sudo apt install certbot python3-certbot-nginx -y
# 获取证书
sudo certbot --nginx -d 你的域名
# 自动续期测试
sudo certbot renew --dry-run
创建 deploy.sh 脚本:
#!/bin/bash
echo "开始部署 Vue 项目..."
# 构建项目
npm run build
# 上传到服务器
rsync -avz -e ssh dist/ root@服务器IP:/var/www/vue-project/dist/
# 重启 Nginx
ssh root@服务器IP "sudo systemctl reload nginx"
echo "部署完成!"
赋予执行权限:
chmod +x deploy.sh
./deploy.sh
确保 Nginx 配置中包含:
location / {
try_files $uri $uri/ /index.html;
}
在 vue.config.js 中配置代理:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://后端API地址',
changeOrigin: true
}
}
}
}
检查路径配置:
// vue.config.js
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? './' : '/'
}
# Nginx 配置
gzip on;
gzip_min_length 1k;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 访问日志
tail -f /var/log/nginx/access.log
# 错误日志
tail -f /var/log/nginx/error.log
# 查看 Nginx 状态
systemctl status nginx
# 重启 Nginx
systemctl restart nginx
这样你的 Vue 项目就成功部署到阿里云服务器了!