本文档详细说明如何使用 nginx 部署 vue3 单页应用,包括本地开发环境和服务端生产环境的配置差异。
1. nginx 基础知识
1.1 什么是 nginx?
nginx 是一个高性能的 http 和反向代理服务器,也是一个 imap/pop3/smtp 服务器。在 web 开发中,主要用途:
- 静态资源服务器:托管 html、css、js、图片等静态文件
- 反向代理:将请求转发到后端服务器
- 负载均衡:将请求分发到多台服务器
1.2 nginx 目录结构
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 整体运行
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
#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 | uriuri uriuri/ /index.html | vue spa 路由支持 |
| gzip | on | 开启压缩,提升加载速度 |
2.3 启动步骤
# 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 完整的服务器配置
# 生产环境配置示例
# 根据 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)
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 本地路径:
root d:/test/vue3-h5/dist; # 使用正斜杠 / root d:\\test\\vue3-h5\\dist; # 或使用双反斜杠转义
linux 服务器路径:
root /var/www/vue3-h5/dist; # linux 标准路径格式
4.3 域名配置差异
本地开发:
server_name localhost; # 本机访问 # 或 server_name 127.0.0.1; # 本机 ip
服务器生产:
server_name your-domain.com; # 你的域名 server_name www.your-domain.com; # 多个域名 server_name 192.168.1.100; # 或直接用服务器 ip
4.4 端口配置差异
本地开发(80 端口可能被占用):
listen 8080; # 如果 80 被占用,可以用其他端口
服务器生产:
listen 80; # http 默认端口 listen 443 ssl http2; # https 端口
5. 完整部署流程
5.1 本地部署步骤
# 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 服务器部署步骤
第一步:准备服务器环境
# 以 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
第二步:上传打包文件
# 方式一:使用 scp 上传 scp -r d:/test/vue3-h5/dist user@server-ip:/var/www/vue3-h5/ # 方式二:使用 ftp 工具(如 filezilla)上传 # 方式三:在服务器上直接打包 # 先上传源码,在服务器上运行 npm run build
第三步:配置 nginx
# 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
第四步:配置域名(如果有)
# 1. 在域名服务商处添加 dns 解析 # 类型: a # 主机: @ # 值: 服务器 ip # 2. 等待 dns 生效(几分钟到几小时) # 3. 测试访问 curl -i http://your-domain.com
第五步:配置 https(推荐)
# 使用 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 本地命令
# 进入 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 服务器命令
# 启动 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 项目相关命令
# 开发环境运行 npm run dev # 生产环境打包 npm run build # 预览打包结果 npm run preview
7. 常见问题排查
7.1 页面空白
可能原因:
- 路由模式问题
- 静态资源路径问题
- 打包配置问题
排查步骤:
# 1. 检查 dist 目录是否有 index.html ls dist/index.html # 2. 检查浏览器控制台错误 # f12 打开开发者工具,查看 console 和 network # 3. 检查 vite.config.ts 的 base 配置 # 如果部署在子路径,需要设置 base
解决方案:
// vite.config.ts
export default defineconfig({
// 部署在根路径
base: '/',
// 如果部署在子路径(如 http://domain.com/app/)
// base: '/app/',
})
7.2 404 not found
可能原因:
- root 路径配置错误
- 静态文件未正确上传
排查步骤:
# 1. 检查 root 路径是否正确 ls /var/www/vue3-h5/dist/index.html # 2. 检查 nginx 配置 sudo nginx -t # 3. 检查文件权限 ls -la /var/www/vue3-h5/dist
解决方案:
# 修复文件权限 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 配置中有:
location / {
try_files $uri $uri/ /index.html;
}
7.4 端口被占用
windows 排查:
# 查看端口占用 netstat -ano | findstr :80 # 结束占用进程(pid 是上面查到的进程 id) taskkill /pid <进程id> /f
linux 排查:
# 查看端口占用 sudo lsof -i :80 # 或 sudo netstat -tlnp | grep :80 # 结束占用进程 sudo kill -9 <pid>
7.5 nginx 配置修改不生效
# 1. 测试配置是否正确 nginx -t # 2. 重载配置 nginx -s reload # windows sudo systemctl reload nginx # linux # 3. 清除浏览器缓存后刷新页面 # ctrl + f5 强制刷新
7.6 跨域问题
问题现象:api 请求报 cors 错误
解决方案一: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 头
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. 本地开发配置模板
# 简化版本地配置
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. 服务器生产配置模板
# 生产环境完整配置
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 |
部署核心流程:
- 本地打包
npm run build - 上传 dist 到服务器
- 配置 nginx 指向 dist 目录
- 配置
try_files支持 vue router - 重载 nginx 配置
- 测试访问
如有问题,优先查看 nginx 错误日志进行排查。
到此这篇关于nginx部署vue3项目完整指南的文章就介绍到这了,更多相关nginx部署vue3内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论