一、准备工作

1.1 本地环境要求

  • Node.js (建议 16.x 或更高版本)
  • npm 或 yarn
  • Vue3 + TypeScript 项目已完成开发

1.2 服务器要求

  • 阿里云 ECS 服务器(Alibaba Cloud Linux)
  • 已配置安全组规则(开放 80、443、22 端口)
  • 拥有服务器的 root 权限或 sudo 权限

二、本地项目打包

2.1 配置生产环境变量

创建 .env.production 文件:

VITE_API_BASE_URL=https://your-api-domain.com
VITE_APP_TITLE=Your App Name

2.2 修改 vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  base: '/', // 如果部署在子路径,修改为 '/子路径/'
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  }
})

2.3 执行打包命令

# 使用 npm
npm run build

# 或使用 yarn
yarn build

打包完成后,项目根目录会生成 dist 文件夹。

三、服务器环境配置

3.1 连接服务器

ssh root@your-server-ip

3.2 安装必要软件

# 更新系统
yum update -y

# 安装 Nginx
yum install nginx -y

# 安装 Node.js (可选,如果需要 SSR)
curl -sL https://rpm.nodesource.com/setup_16.x | bash -
yum install nodejs -y

# 启动 Nginx
systemctl start nginx
systemctl enable nginx

3.3 配置防火墙

# 开放 HTTP 和 HTTPS 端口
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

四、上传文件到服务器

4.1 方法一:使用 SCP 命令

在本地终端执行:

# 上传整个 dist 文件夹
scp -r ./dist/* root@your-server-ip:/home/admin/apps/

4.2 方法二:使用 FTP 工具

推荐工具:

  • FileZilla
  • WinSCP (Windows)
  • Cyberduck (Mac)

上传步骤:

  1. 连接服务器(使用 SFTP 协议)
  2. 导航到 /usr/share/nginx/html/
  3. 上传 dist 文件夹内的所有文件

4.3 方法三:使用 rsync(推荐)

# 安装 rsync(如果没有)
yum install rsync -y

# 同步文件
rsync -avz --delete ./dist/ root@your-server-ip:/usr/share/nginx/html/

五、配置 Nginx

5.1 创建 Nginx 配置文件

vim /etc/nginx/conf.d/vue-app.conf

5.2 添加配置内容

server {
    listen 80;
    server_name 18; # 替换为你的域名或 IP

    root /home/admin/apps/html;
    index index.html;

    # gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;

    # Vue Router 历史模式支持
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # API 代理(如果需要)
    location /api {
        proxy_pass http://localhost:8080; # 后端 API 地址
        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_set_header X-Forwarded-Proto $scheme;
    }
}

5.3 测试并重启 Nginx

# 测试配置
sudo nginx -t


# 重启 Nginx
systemctl restart nginx

六、HTTPS 配置(可选但推荐)

6.1 安装 Certbot

yum install epel-release -y
yum install certbot python3-certbot-nginx -y

6.2 获取 SSL 证书

certbot --nginx -d your-domain.com
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐