Nginx 部署 Vue3 项目完整指南

Nginx 部署 Vue3 项目完整指南

本文档详细说明如何使用 Nginx 部署 Vue3 单页应用,包括本地开发环境和服务端生产环境的配置差异。


目录

  1. [Nginx 基础知识](#Nginx 基础知识 "#1-nginx-%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86")
  2. 本地开发环境配置
  3. 服务器生产环境配置
  4. 本地与服务器的配置差异
  5. 完整部署流程
  6. 常用命令速查
  7. 常见问题排查

1. Nginx 基础知识

1.1 什么是 Nginx?

Nginx 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 服务器。在 Web 开发中,主要用途:

  • 静态资源服务器:托管 HTML、CSS、JS、图片等静态文件
  • 反向代理:将请求转发到后端服务器
  • 负载均衡:将请求分发到多台服务器

1.2 Nginx 目录结构

bash 复制代码
nginx-1.24.0/
├── conf/               # 配置文件目录
│   ├── nginx.conf      # 主配置文件(最重要)
│   ├── mime.types      # 文件类型映射
│   └── ...
├── html/               # 默认静态文件目录
│   ├── index.html
│   └── 50x.html
├── logs/               # 日志目录
│   ├── access.log      # 访问日志
│   └── error.log       # 错误日志
├── temp/               # 临时文件目录
├── contrib/            # 扩展模块
├── docs/               # 文档
└── nginx.exe           # Windows 可执行文件

1.3 配置文件基本结构

nginx 复制代码
# 全局块 - 影响 Nginx 整体运行
worker_processes  1;  # 工作进程数

# events 块 - 影响网络连接
events {
    worker_connections  1024;  # 每个进程最大连接数
}

# http 块 - Web 服务器配置
http {
    # http 全局配置
    include       mime.types;

    # server 块 - 虚拟主机配置
    server {
        listen       80;        # 监听端口
        server_name  localhost; # 域名/IP

        # location 块 - 路由匹配
        location / {
            root   html;        # 静态文件目录
            index  index.html;  # 默认首页
        }
    }
}

2. 本地开发环境配置

2.1 当前项目配置

配置文件位置C:\Users\EDY\Downloads\nginx-1.24.0\nginx-1.24.0\conf\nginx.conf

nginx 复制代码
#user  nobody;
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        # 你的 Vue3 项目打包后的目录
        root   D:/test/vue3-h5/dist;
        index  index.html index.htm;

        location / {
            # Vue 是单页应用,所有路由都要返回 index.html
            try_files $uri $uri/ /index.html;
        }

        # 开启 gzip 压缩,加快加载速度
        gzip on;
        gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
        gzip_min_length 1000;

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2.2 配置详解

配置项 说明
listen 80 监听端口,本地访问用 localhost:80
server_name localhost 本地测试用 localhost
root D:/test/vue3-h5/dist 指向本地打包目录
try_files <math xmlns="http://www.w3.org/1998/Math/MathML"> u r i uri </math>uriuri/ /index.html Vue SPA 路由支持
gzip on 开启压缩,提升加载速度

2.3 启动步骤

bash 复制代码
# 1. 进入 Nginx 目录
cd C:\Users\EDY\Downloads\nginx-1.24.0\nginx-1.24.0

# 2. 启动 Nginx
start nginx

# 3. 访问测试
# 浏览器打开 http://localhost

3. 服务器生产环境配置

3.1 完整的服务器配置

nginx 复制代码
# 生产环境配置示例

# 根据 CPU 核心数设置工作进程
worker_processes  auto;

# 错误日志级别设为 warn
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    # 最大连接数,根据服务器配置调整
    worker_connections  2048;
    # 提高并发性能
    use epoll;
    multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # 日志格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    # 访问日志
    access_log  /var/log/nginx/access.log  main;

    # 性能优化
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
    types_hash_max_size 2048;

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

    # 安全头配置
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # 上传文件大小限制(如果需要)
    client_max_body_size 10M;

    # Vue 应用服务器配置
    server {
        listen       80;
        server_name  your-domain.com;  # 替换为你的域名

        # 静态文件目录(服务器上的路径)
        root   /var/www/vue3-h5/dist;
        index  index.html index.htm;

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

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

        # 禁止访问隐藏文件
        location ~ /\. {
            deny all;
        }

        # 错误页面
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
    }

    # HTTPS 配置(推荐使用)
    # server {
    #     listen       443 ssl http2;
    #     server_name  your-domain.com;
    #
    #     # SSL 证书配置
    #     ssl_certificate      /etc/nginx/ssl/your-domain.com.pem;
    #     ssl_certificate_key  /etc/nginx/ssl/your-domain.com.key;
    #
    #     # SSL 优化配置
    #     ssl_session_timeout  1d;
    #     ssl_session_cache    shared:SSL:50m;
    #     ssl_session_tickets  off;
    #
    #     # 现代 SSL 配置
    #     ssl_protocols TLSv1.2 TLSv1.3;
    #     ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    #     ssl_prefer_server_ciphers  on;
    #
    #     # HSTS
    #     add_header Strict-Transport-Security "max-age=31536000" always;
    #
    #     root   /var/www/vue3-h5/dist;
    #     index  index.html;
    #
    #     location / {
    #         try_files $uri $uri/ /index.html;
    #     }
    # }

    # HTTP 自动跳转 HTTPS
    # server {
    #     listen 80;
    #     server_name your-domain.com;
    #     return 301 https://$server_name$request_uri;
    # }
}

3.2 反向代理配置(如果需要调用后端 API)

nginx 复制代码
server {
    listen       80;
    server_name  your-domain.com;

    root   /var/www/vue3-h5/dist;
    index  index.html;

    # 前端路由
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 后端 API 代理
    location /api/ {
        proxy_pass http://backend-server:8080/;  # 后端服务地址
        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;

        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

4. 本地与服务器的配置差异

4.1 差异对比表

配置项 本地开发环境 服务器生产环境 说明
worker_processes 1 auto 生产环境根据 CPU 核心数自动设置
worker_connections 1024 2048+ 服务器并发要求更高
server_name localhost your-domain.com 本地用 localhost,服务器用域名
root 路径 D:/test/vue3-h5/dist /var/www/vue3-h5/dist Windows 和 Linux 路径格式不同
error_log 注释掉 /var/log/nginx/error.log warn 生产环境需要记录日志
access_log 注释掉 /var/log/nginx/access.log main 生产环境需要访问日志
gzip 基础配置 完整配置 生产环境需要更细致的压缩配置
缓存配置 生产环境需要静态资源缓存
安全头 生产环境需要安全防护
HTTPS 推荐 生产环境强烈推荐 HTTPS
反向代理 通常不需要 常需要 生产环境常需要代理后端 API

4.2 路径格式差异

Windows 本地路径

nginx 复制代码
root   D:/test/vue3-h5/dist;    # 使用正斜杠 /
root   D:\\test\\vue3-h5\\dist;  # 或使用双反斜杠转义

Linux 服务器路径

nginx 复制代码
root   /var/www/vue3-h5/dist;   # Linux 标准路径格式

4.3 域名配置差异

本地开发

nginx 复制代码
server_name  localhost;          # 本机访问
# 或
server_name  127.0.0.1;         # 本机 IP

服务器生产

nginx 复制代码
server_name  your-domain.com;    # 你的域名
server_name  www.your-domain.com; # 多个域名
server_name  192.168.1.100;      # 或直接用服务器 IP

4.4 端口配置差异

本地开发(80 端口可能被占用):

nginx 复制代码
listen  8080;   # 如果 80 被占用,可以用其他端口

服务器生产

nginx 复制代码
listen  80;     # HTTP 默认端口
listen  443 ssl http2;  # HTTPS 端口

5. 完整部署流程

5.1 本地部署步骤

bash 复制代码
# 1. 打包 Vue 项目
cd D:/test/vue3-h5
npm run build
# 打包后会生成 dist 目录

# 2. 修改 Nginx 配置
# 编辑 C:\Users\EDY\Downloads\nginx-1.24.0\nginx-1.24.0\conf\nginx.conf
# 设置 root 指向 dist 目录

# 3. 启动 Nginx
cd C:\Users\EDY\Downloads\nginx-1.24.0\nginx-1.24.0
start nginx

# 4. 访问测试
# 浏览器打开 http://localhost

5.2 服务器部署步骤

第一步:准备服务器环境
bash 复制代码
# 以 Ubuntu/Debian 为例
# 1. 更新系统
sudo apt update && sudo apt upgrade -y

# 2. 安装 Nginx
sudo apt install nginx -y

# 3. 检查 Nginx 状态
sudo systemctl status nginx

# 4. 设置开机自启
sudo systemctl enable nginx
第二步:上传打包文件
bash 复制代码
# 方式一:使用 scp 上传
scp -r D:/test/vue3-h5/dist user@server-ip:/var/www/vue3-h5/

# 方式二:使用 FTP 工具(如 FileZilla)上传

# 方式三:在服务器上直接打包
# 先上传源码,在服务器上运行 npm run build
第三步:配置 Nginx
bash 复制代码
# 1. 创建配置文件
sudo nano /etc/nginx/sites-available/vue3-h5

# 2. 写入配置内容(参考上面的生产环境配置)

# 3. 创建软链接启用配置
sudo ln -s /etc/nginx/sites-available/vue3-h5 /etc/nginx/sites-enabled/

# 4. 测试配置是否正确
sudo nginx -t

# 5. 重载 Nginx
sudo systemctl reload nginx
第四步:配置域名(如果有)
bash 复制代码
# 1. 在域名服务商处添加 DNS 解析
#    类型: A
#    主机: @
#    值: 服务器 IP

# 2. 等待 DNS 生效(几分钟到几小时)

# 3. 测试访问
curl -I http://your-domain.com
第五步:配置 HTTPS(推荐)
bash 复制代码
# 使用 Let's Encrypt 免费证书

# 1. 安装 Certbot
sudo apt install certbot python3-certbot-nginx -y

# 2. 自动配置 HTTPS
sudo certbot --nginx -d your-domain.com -d www.your-domain.com

# 3. 测试自动续期
sudo certbot renew --dry-run

# Certbot 会自动修改 Nginx 配置,添加 SSL 相关配置

5.3 部署检查清单

  • 项目已打包(npm run build)
  • dist 目录已上传到服务器
  • Nginx 已安装并运行
  • Nginx 配置文件已正确设置
  • root 路径指向正确的 dist 目录
  • server_name 已设置正确的域名/IP
  • 防火墙已开放 80/443 端口
  • 域名 DNS 已解析到服务器
  • HTTPS 证书已配置(推荐)
  • 网站可以正常访问

6. 常用命令速查

6.1 Windows 本地命令

bash 复制代码
# 进入 Nginx 目录
cd C:\Users\EDY\Downloads\nginx-1.24.0\nginx-1.24.0

# 启动 Nginx
start nginx

# 停止 Nginx
nginx -s stop          # 快速停止
nginx -s quit          # 优雅停止(处理完当前请求)

# 重载配置(修改配置后)
nginx -s reload

# 重新打开日志文件
nginx -s reopen

# 测试配置文件语法
nginx -t

# 查看 Nginx 版本
nginx -v

# 查看 Nginx 进程
tasklist | findstr nginx

# 强制结束所有 Nginx 进程
taskkill /F /IM nginx.exe

6.2 Linux 服务器命令

bash 复制代码
# 启动 Nginx
sudo systemctl start nginx

# 停止 Nginx
sudo systemctl stop nginx

# 重启 Nginx
sudo systemctl restart nginx

# 重载配置(不中断服务)
sudo systemctl reload nginx

# 查看 Nginx 状态
sudo systemctl status nginx

# 设置开机自启
sudo systemctl enable nginx

# 取消开机自启
sudo systemctl disable nginx

# 测试配置文件
sudo nginx -t

# 查看 Nginx 版本
nginx -v

# 查看错误日志
sudo tail -f /var/log/nginx/error.log

# 查看访问日志
sudo tail -f /var/log/nginx/access.log

6.3 Vue 项目相关命令

bash 复制代码
# 开发环境运行
npm run dev

# 生产环境打包
npm run build

# 预览打包结果
npm run preview

7. 常见问题排查

7.1 页面空白

可能原因

  1. 路由模式问题
  2. 静态资源路径问题
  3. 打包配置问题

排查步骤

bash 复制代码
# 1. 检查 dist 目录是否有 index.html
ls dist/index.html

# 2. 检查浏览器控制台错误
# F12 打开开发者工具,查看 Console 和 Network

# 3. 检查 vite.config.ts 的 base 配置
# 如果部署在子路径,需要设置 base

解决方案

typescript 复制代码
// vite.config.ts
export default defineConfig({
  // 部署在根路径
  base: '/',

  // 如果部署在子路径(如 http://domain.com/app/)
  // base: '/app/',
})

7.2 404 Not Found

可能原因

  1. root 路径配置错误
  2. 静态文件未正确上传

排查步骤

bash 复制代码
# 1. 检查 root 路径是否正确
ls /var/www/vue3-h5/dist/index.html

# 2. 检查 Nginx 配置
sudo nginx -t

# 3. 检查文件权限
ls -la /var/www/vue3-h5/dist

解决方案

bash 复制代码
# 修复文件权限
sudo chown -R www-data:www-data /var/www/vue3-h5
sudo chmod -R 755 /var/www/vue3-h5

7.3 刷新页面 404

原因:Vue Router 使用 history 模式,需要 Nginx 配置支持

解决方案:确保 Nginx 配置中有:

nginx 复制代码
location / {
    try_files $uri $uri/ /index.html;
}

7.4 端口被占用

Windows 排查

bash 复制代码
# 查看端口占用
netstat -ano | findstr :80

# 结束占用进程(PID 是上面查到的进程 ID)
taskkill /PID <进程ID> /F

Linux 排查

bash 复制代码
# 查看端口占用
sudo lsof -i :80

# 或
sudo netstat -tlnp | grep :80

# 结束占用进程
sudo kill -9 <PID>

7.5 Nginx 配置修改不生效

bash 复制代码
# 1. 测试配置是否正确
nginx -t

# 2. 重载配置
nginx -s reload      # Windows
sudo systemctl reload nginx  # Linux

# 3. 清除浏览器缓存后刷新页面
# Ctrl + F5 强制刷新

7.6 跨域问题

问题现象:API 请求报 CORS 错误

解决方案一:Nginx 反向代理

nginx 复制代码
location /api/ {
    proxy_pass http://backend-server:8080/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

解决方案二:添加 CORS 头

nginx 复制代码
location /api/ {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';

    if ($request_method = 'OPTIONS') {
        return 204;
    }

    proxy_pass http://backend-server:8080/;
}

附录:配置文件模板

A. 本地开发配置模板

nginx 复制代码
# 简化版本地配置
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        root   D:/test/vue3-h5/dist;
        index  index.html;

        location / {
            try_files $uri $uri/ /index.html;
        }

        gzip on;
        gzip_types text/plain text/css application/json application/javascript;
    }
}

B. 服务器生产配置模板

nginx 复制代码
# 生产环境完整配置
worker_processes  auto;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  2048;
    use epoll;
    multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;

    gzip  on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 1000;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

    server {
        listen       80;
        server_name  your-domain.com;

        root   /var/www/vue3-h5/dist;
        index  index.html;

        location / {
            try_files $uri $uri/ /index.html;
        }

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

        location ~ /\. {
            deny all;
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
}

总结

环境 关键配置 访问方式
本地 localhost + 本地路径 http://localhost
服务器 域名/IP + 服务器路径 + 优化配置 your-domain.com

部署核心流程:

  1. 本地打包 npm run build
  2. 上传 dist 到服务器
  3. 配置 Nginx 指向 dist 目录
  4. 配置 try_files 支持 Vue Router
  5. 重载 Nginx 配置
  6. 测试访问

如有问题,优先查看 Nginx 错误日志进行排查。

相关推荐
臣妾没空2 小时前
Elpis 全栈框架:从构建到发布的完整实践总结
前端·后端
决斗小饼干2 小时前
跨语言移植手记:把 TypeScript 的 Codex SDK 请进 .NET 世界
前端·javascript·typescript
小码哥_常2 小时前
Android Intent.setAction失效报错排查与修复全方案
前端
进击的尘埃2 小时前
Vitest 浏览器模式:别再用 jsdom 骗自己了
javascript
bluceli2 小时前
JavaScript模块化深度解析:从CommonJS到ES Modules的演进之路
前端·javascript
前端人类学2 小时前
前端输入框禁用:disabled、readonly 与.prop (‘disabled‘, true) 完全解析
前端·javascript
优秀稳妥的JiaJi2 小时前
分享一篇后台管理系统的通用skills
前端·vue.js·前端框架
程序员阿耶3 小时前
移动端适配终极指南:rem 原理与实战
前端
user86158185781543 小时前
彻底解决 Dart Sass 升级导致的 @import 弃用警告及 Vite 缓存踩坑实录
前端