Nginx部署Vue3項目完整指南
本文檔詳細(xì)說明如何使用 Nginx 部署 Vue3 單頁應(yīng)用,包括本地開發(fā)環(huán)境和服務(wù)端生產(chǎn)環(huán)境的配置差異。
1. Nginx 基礎(chǔ)知識
1.1 什么是 Nginx?
Nginx 是一個高性能的 HTTP 和反向代理服務(wù)器,也是一個 IMAP/POP3/SMTP 服務(wù)器。在 Web 開發(fā)中,主要用途:
- 靜態(tài)資源服務(wù)器:托管 HTML、CSS、JS、圖片等靜態(tài)文件
- 反向代理:將請求轉(zhuǎn)發(fā)到后端服務(wù)器
- 負(fù)載均衡:將請求分發(fā)到多臺服務(wù)器
1.2 Nginx 目錄結(jié)構(gòu)
nginx-1.24.0/ ├── conf/ # 配置文件目錄 │ ├── nginx.conf # 主配置文件(最重要) │ ├── mime.types # 文件類型映射 │ └── ... ├── html/ # 默認(rèn)靜態(tài)文件目錄 │ ├── index.html │ └── 50x.html ├── logs/ # 日志目錄 │ ├── access.log # 訪問日志 │ └── error.log # 錯誤日志 ├── temp/ # 臨時文件目錄 ├── contrib/ # 擴展模塊 ├── docs/ # 文檔 └── nginx.exe # Windows 可執(zhí)行文件
1.3 配置文件基本結(jié)構(gòu)
# 全局塊 - 影響 Nginx 整體運行
worker_processes 1; # 工作進程數(shù)
# events 塊 - 影響網(wǎng)絡(luò)連接
events {
worker_connections 1024; # 每個進程最大連接數(shù)
}
# http 塊 - Web 服務(wù)器配置
http {
# http 全局配置
include mime.types;
# server 塊 - 虛擬主機配置
server {
listen 80; # 監(jiān)聽端口
server_name localhost; # 域名/IP
# location 塊 - 路由匹配
location / {
root html; # 靜態(tài)文件目錄
index index.html; # 默認(rèn)首頁
}
}
}
2. 本地開發(fā)環(huán)境配置
2.1 當(dāng)前項目配置
配置文件位置: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 是單頁應(yīng)用,所有路由都要返回 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 | 監(jiān)聽端口,本地訪問用 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. 服務(wù)器生產(chǎn)環(huán)境配置
3.1 完整的服務(wù)器配置
# 生產(chǎn)環(huán)境配置示例
# 根據(jù) CPU 核心數(shù)設(shè)置工作進程
worker_processes auto;
# 錯誤日志級別設(shè)為 warn
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
# 最大連接數(shù),根據(jù)服務(wù)器配置調(diào)整
worker_connections 2048;
# 提高并發(fā)性能
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;
# 性能優(yōu)化
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 應(yīng)用服務(wù)器配置
server {
listen 80;
server_name your-domain.com; # 替換為你的域名
# 靜態(tài)文件目錄(服務(wù)器上的路徑)
root /var/www/vue3-h5/dist;
index index.html index.htm;
# Vue Router history 模式支持
location / {
try_files $uri $uri/ /index.html;
}
# 靜態(tài)資源緩存(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 優(yōu)化配置
# ssl_session_timeout 1d;
# ssl_session_cache shared:SSL:50m;
# ssl_session_tickets off;
#
# # 現(xiàn)代 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 自動跳轉(zhuǎn) HTTPS
# server {
# listen 80;
# server_name your-domain.com;
# return 301 https://$server_name$request_uri;
# }
}
3.2 反向代理配置(如果需要調(diào)用后端 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/; # 后端服務(wù)地址
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;
# 超時設(shè)置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
4. 本地與服務(wù)器的配置差異
4.1 差異對比表
| 配置項 | 本地開發(fā)環(huán)境 | 服務(wù)器生產(chǎn)環(huán)境 | 說明 |
|---|---|---|---|
| worker_processes | 1 | auto | 生產(chǎn)環(huán)境根據(jù) CPU 核心數(shù)自動設(shè)置 |
| worker_connections | 1024 | 2048+ | 服務(wù)器并發(fā)要求更高 |
| server_name | localhost | your-domain.com | 本地用 localhost,服務(wù)器用域名 |
| root 路徑 | D:/test/vue3-h5/dist | /var/www/vue3-h5/dist | Windows 和 Linux 路徑格式不同 |
| error_log | 注釋掉 | /var/log/nginx/error.log warn | 生產(chǎn)環(huán)境需要記錄日志 |
| access_log | 注釋掉 | /var/log/nginx/access.log main | 生產(chǎn)環(huán)境需要訪問日志 |
| gzip | 基礎(chǔ)配置 | 完整配置 | 生產(chǎn)環(huán)境需要更細(xì)致的壓縮配置 |
| 緩存配置 | 無 | 有 | 生產(chǎn)環(huán)境需要靜態(tài)資源緩存 |
| 安全頭 | 無 | 有 | 生產(chǎn)環(huán)境需要安全防護 |
| HTTPS | 無 | 推薦 | 生產(chǎn)環(huán)境強烈推薦 HTTPS |
| 反向代理 | 通常不需要 | 常需要 | 生產(chǎn)環(huán)境常需要代理后端 API |
4.2 路徑格式差異
Windows 本地路徑:
root D:/test/vue3-h5/dist; # 使用正斜杠 / root D:\\test\\vue3-h5\\dist; # 或使用雙反斜杠轉(zhuǎn)義
Linux 服務(wù)器路徑:
root /var/www/vue3-h5/dist; # Linux 標(biāo)準(zhǔn)路徑格式
4.3 域名配置差異
本地開發(fā):
server_name localhost; # 本機訪問 # 或 server_name 127.0.0.1; # 本機 IP
服務(wù)器生產(chǎn):
server_name your-domain.com; # 你的域名 server_name www.your-domain.com; # 多個域名 server_name 192.168.1.100; # 或直接用服務(wù)器 IP
4.4 端口配置差異
本地開發(fā)(80 端口可能被占用):
listen 8080; # 如果 80 被占用,可以用其他端口
服務(wù)器生產(chǎn):
listen 80; # HTTP 默認(rèn)端口 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 # 設(shè)置 root 指向 dist 目錄 # 3. 啟動 Nginx cd C:\Users\EDY\Downloads\nginx-1.24.0\nginx-1.24.0 start nginx # 4. 訪問測試 # 瀏覽器打開 http://localhost
5.2 服務(wù)器部署步驟
第一步:準(zhǔn)備服務(wù)器環(huán)境
# 以 Ubuntu/Debian 為例 # 1. 更新系統(tǒng) sudo apt update && sudo apt upgrade -y # 2. 安裝 Nginx sudo apt install nginx -y # 3. 檢查 Nginx 狀態(tài) sudo systemctl status nginx # 4. 設(shè)置開機自啟 sudo systemctl enable nginx
第二步:上傳打包文件
# 方式一:使用 scp 上傳 scp -r D:/test/vue3-h5/dist user@server-ip:/var/www/vue3-h5/ # 方式二:使用 FTP 工具(如 FileZilla)上傳 # 方式三:在服務(wù)器上直接打包 # 先上傳源碼,在服務(wù)器上運行 npm run build
第三步:配置 Nginx
# 1. 創(chuàng)建配置文件 sudo nano /etc/nginx/sites-available/vue3-h5 # 2. 寫入配置內(nèi)容(參考上面的生產(chǎn)環(huán)境配置) # 3. 創(chuàng)建軟鏈接啟用配置 sudo ln -s /etc/nginx/sites-available/vue3-h5 /etc/nginx/sites-enabled/ # 4. 測試配置是否正確 sudo nginx -t # 5. 重載 Nginx sudo systemctl reload nginx
第四步:配置域名(如果有)
# 1. 在域名服務(wù)商處添加 DNS 解析 # 類型: A # 主機: @ # 值: 服務(wù)器 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. 測試自動續(xù)期 sudo certbot renew --dry-run # Certbot 會自動修改 Nginx 配置,添加 SSL 相關(guān)配置
5.3 部署檢查清單
- 項目已打包(npm run build)
- dist 目錄已上傳到服務(wù)器
- Nginx 已安裝并運行
- Nginx 配置文件已正確設(shè)置
- root 路徑指向正確的 dist 目錄
- server_name 已設(shè)置正確的域名/IP
- 防火墻已開放 80/443 端口
- 域名 DNS 已解析到服務(wù)器
- HTTPS 證書已配置(推薦)
- 網(wǎng)站可以正常訪問
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 # 優(yōu)雅停止(處理完當(dāng)前請求) # 重載配置(修改配置后) nginx -s reload # 重新打開日志文件 nginx -s reopen # 測試配置文件語法 nginx -t # 查看 Nginx 版本 nginx -v # 查看 Nginx 進程 tasklist | findstr nginx # 強制結(jié)束所有 Nginx 進程 taskkill /F /IM nginx.exe
6.2 Linux 服務(wù)器命令
# 啟動 Nginx sudo systemctl start nginx # 停止 Nginx sudo systemctl stop nginx # 重啟 Nginx sudo systemctl restart nginx # 重載配置(不中斷服務(wù)) sudo systemctl reload nginx # 查看 Nginx 狀態(tài) sudo systemctl status nginx # 設(shè)置開機自啟 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 項目相關(guān)命令
# 開發(fā)環(huán)境運行 npm run dev # 生產(chǎn)環(huán)境打包 npm run build # 預(yù)覽打包結(jié)果 npm run preview
7. 常見問題排查
7.1 頁面空白
可能原因:
- 路由模式問題
- 靜態(tài)資源路徑問題
- 打包配置問題
排查步驟:
# 1. 檢查 dist 目錄是否有 index.html ls dist/index.html # 2. 檢查瀏覽器控制臺錯誤 # F12 打開開發(fā)者工具,查看 Console 和 Network # 3. 檢查 vite.config.ts 的 base 配置 # 如果部署在子路徑,需要設(shè)置 base
解決方案:
// vite.config.ts
export default defineConfig({
// 部署在根路徑
base: '/',
// 如果部署在子路徑(如 http://domain.com/app/)
// base: '/app/',
})
7.2 404 Not Found
可能原因:
- root 路徑配置錯誤
- 靜態(tài)文件未正確上傳
排查步驟:
# 1. 檢查 root 路徑是否正確 ls /var/www/vue3-h5/dist/index.html # 2. 檢查 Nginx 配置 sudo nginx -t # 3. 檢查文件權(quán)限 ls -la /var/www/vue3-h5/dist
解決方案:
# 修復(fù)文件權(quán)限 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 # 結(jié)束占用進程(PID 是上面查到的進程 ID) taskkill /PID <進程ID> /F
Linux 排查:
# 查看端口占用 sudo lsof -i :80 # 或 sudo netstat -tlnp | grep :80 # 結(jié)束占用進程 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 跨域問題
問題現(xiàn)象: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. 本地開發(fā)配置模板
# 簡化版本地配置
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. 服務(wù)器生產(chǎn)配置模板
# 生產(chǎn)環(huán)境完整配置
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;
}
}
}
總結(jié)
| 環(huán)境 | 關(guān)鍵配置 | 訪問方式 |
|---|---|---|
| 本地 | localhost + 本地路徑 | http://localhost |
| 服務(wù)器 | 域名/IP + 服務(wù)器路徑 + 優(yōu)化配置 | your-domain.com |
部署核心流程:
- 本地打包
npm run build - 上傳 dist 到服務(wù)器
- 配置 Nginx 指向 dist 目錄
- 配置
try_files支持 Vue Router - 重載 Nginx 配置
- 測試訪問
如有問題,優(yōu)先查看 Nginx 錯誤日志進行排查。
到此這篇關(guān)于Nginx部署Vue3項目完整指南的文章就介紹到這了,更多相關(guān)Nginx部署Vue3內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Nginx+RTMP+nginx-http-flv-module環(huán)境搭建
本文主要介紹了Nginx+RTMP+nginx-http-flv-module環(huán)境搭建,搭建方式可用于直播、視頻會議等場景,同時支持HTTP-FLV,方便在瀏覽器中進行播放2024-03-03
解決Nginx網(wǎng)關(guān)超時出現(xiàn)504 GATEWAY TIMEOUT的問題
這篇文章主要給大家介紹了如何解決Nginx網(wǎng)關(guān)超時出現(xiàn)504 GATEWAY TIMEOUT的問題,文章通過代碼示例和圖文結(jié)合介紹的非常詳細(xì),有遇到相同問題的朋友可以參考閱讀本文2023-11-11

