🚀 Nginx 是后端开发必备技能。本文从零开始讲透 Nginx 配置,涵盖反向代理、负载均衡、HTTPS、静态资源缓存、Gzip 压缩等核心场景,每个配置都有完整示例,收藏备用!
一、Nginx 核心概念
1.1 Nginx 是什么?
Nginx(发音"Engine X")是高性能的 HTTP 服务器和反向代理服务器:
| 角色 | 说明 |
|---|---|
| 静态文件服务器 | 直接处理 HTML/CSS/JS/图片,速度极快 |
| 反向代理 | 将请求转发到后端服务(Node.js/Java/Python) |
| 负载均衡 | 多台服务器分摊流量 |
| SSL/TLS 终止 | 统一处理 HTTPS,后端无需关心证书 |
| 限流/防刷 | 控制请求速率,防止 DDoS |
Nginx 核心架构:
- 1 个 Master 进程(管理)
- N 个 Worker 进程(处理请求,N = CPU核数)
- 事件驱动 + 非阻塞 IO,单机轻松支撑 10 万并发
二、安装与基础配置
2.1 安装 Nginx
bash
# CentOS / 宝塔(已有可跳过)
sudo yum install -y nginx
# Ubuntu / Debian
sudo apt update && sudo apt install -y nginx
# 启动并设置开机启动
sudo systemctl start nginx
sudo systemctl enable nginx
# 验证安装
nginx -v # nginx/1.24.0
2.2 配置文件结构
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 自定义配置目录(推荐在这里写)
│ ├── default.conf
│ ├── mysite.conf
│ └── api.conf
└── sites-enabled/ # Ubuntu 风格(软链接)
2.3 nginx.conf 全局配置解析
nginx
# /etc/nginx/nginx.conf
# 工作进程数(设为 auto,自动匹配 CPU 核数)
worker_processes auto;
# 错误日志
error_log /var/log/nginx/error.log warn;
# PID 文件
pid /var/run/nginx.pid;
events {
# 每个 worker 进程最大连接数
worker_connections 1024;
# 使用 epoll(Linux 高效 IO 模型)
use epoll;
# 允许一次性接受多个连接
multi_accept on;
}
http {
# 包含 MIME 类型定义
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;
# 隐藏版本号(安全)
server_tokens off;
# 包含所有站点配置
include /etc/nginx/conf.d/*.conf;
}
三、核心场景配置
3.1 静态网站部署(Vue3/React 前端)
nginx
# /etc/nginx/conf.d/frontend.conf
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
# 前端打包文件目录
root /var/www/dist;
index index.html;
# ===== Vue Router / React Router History 模式支持 =====
# 关键:所有路径都返回 index.html,让前端路由处理
location / {
try_files $uri $uri/ /index.html;
}
# ===== 静态资源长期缓存 =====
# 带 hash 的文件(如 app.a1b2c3.js)永久缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
expires max;
add_header Cache-Control "public, immutable";
access_log off; # 不记录静态资源访问日志,减少 IO
}
# HTML 文件不缓存(确保前端更新能及时生效)
location ~* \.html$ {
expires -1;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
# ===== Gzip 压缩 =====
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
image/svg+xml;
gzip_vary on;
gzip_proxied any;
}
3.2 反向代理(Node.js / Java 后端)
nginx
# /etc/nginx/conf.d/api.conf
server {
listen 80;
server_name api.yourdomain.com;
# ===== 反向代理到 Node.js(端口3000)=====
location /api/ {
# 转发到后端
proxy_pass http://127.0.0.1:3000;
# 必须设置的 Header
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 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓冲区设置(提高性能)
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 16k;
}
# ===== WebSocket 支持 =====
location /ws/ {
proxy_pass http://127.0.0.1:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s; # WebSocket 长连接,超时设大
}
# ===== 文件上传代理 =====
location /upload/ {
proxy_pass http://127.0.0.1:3000;
client_max_body_size 100m; # 允许最大 100MB 文件
proxy_request_buffering off; # 大文件不缓冲,直接流式转发
}
}
3.3 负载均衡
nginx
# /etc/nginx/conf.d/loadbalance.conf
# ===== 定义上游服务器组 =====
upstream backend_servers {
# 负载均衡策略:
# 默认:轮询(Round Robin)
# ip_hash:同一IP总访问同一服务器(粘性会话)
# least_conn:最少连接数
ip_hash; # 会话保持,适合有状态服务
server 192.168.1.10:8080 weight=3; # weight=权重,流量占比更大
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 weight=1;
# 备用服务器(只有其他服务器都挂了才用)
server 192.168.1.13:8080 backup;
# 健康检查(需要 Nginx Plus 或 nginx_upstream_check_module)
# 这里用 max_fails 和 fail_timeout 做基础故障转移
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name app.yourdomain.com;
location / {
proxy_pass http://backend_servers;
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_next_upstream error timeout http_500 http_502 http_503;
}
}
四、HTTPS 配置
4.1 Let's Encrypt 免费 SSL 证书
bash
# 安装 Certbot
sudo apt install -y certbot python3-certbot-nginx
# 申请证书(自动修改 Nginx 配置)
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
# 自动续期(已自动创建 cron 任务,验证方式)
sudo certbot renew --dry-run
4.2 HTTPS 完整配置
nginx
# /etc/nginx/conf.d/https.conf
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
# HTTP 强制跳转 HTTPS
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
# ===== SSL 证书 =====
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
# ===== SSL 安全配置 =====
ssl_protocols TLSv1.2 TLSv1.3; # 禁用旧版本(TLSv1.0/1.1)
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# SSL 会话缓存(提高性能,减少握手次数)
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# OCSP Stapling(证书状态在线查询)
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
# HSTS(告诉浏览器永远用 HTTPS)
add_header Strict-Transport-Security "max-age=63072000" always;
# 安全 Header
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
root /var/www/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
五、性能优化配置
5.1 Gzip + Brotli 压缩
nginx
http {
# Gzip(通用支持)
gzip on;
gzip_min_length 1k;
gzip_comp_level 5; # 1-9,越高压缩率越高但 CPU 消耗越多,5 是平衡点
gzip_types
text/plain
text/css
text/javascript
application/json
application/javascript
application/x-javascript
application/xml
image/svg+xml;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
# 预压缩文件(Vite/Webpack 构建时生成 .gz 文件,Nginx 直接返回)
gzip_static on;
}
5.2 限流配置
nginx
http {
# 定义限流区(IP 维度,每秒 10 个请求)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
# 定义连接数限制
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location /api/ {
# 应用限流(burst=20 允许短暂突发,nodelay 不排队直接拒绝)
limit_req zone=api_limit burst=20 nodelay;
# 每IP最多50个并发连接
limit_conn conn_limit 50;
# 限流时返回 429
limit_req_status 429;
proxy_pass http://127.0.0.1:3000;
}
}
}
六、常见问题解决
❌ 问题1:Vue3 刷新页面 404
nginx
# 原因:Nginx 找不到路由对应的文件
# 解决:加 try_files,所有请求都返回 index.html
location / {
try_files $uri $uri/ /index.html;
# ✅ $uri:先找对应文件
# ✅ $uri/:再找目录
# ✅ /index.html:都找不到就返回首页
}
❌ 问题2:跨域(CORS)问题
nginx
location /api/ {
proxy_pass http://127.0.0.1:3000;
# 方法1:在 Nginx 层处理 CORS(不推荐,在后端处理更好)
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Content-Type';
add_header 'Access-Control-Max-Age' 1728000;
return 204;
}
# 方法2(推荐):代理到后端,让后端处理 CORS
# proxy_pass 后后端会返回正确的 CORS 头
}
❌ 问题3:上传大文件 413 错误
nginx
server {
# 默认只允许 1MB,增大限制
client_max_body_size 200m;
# 上传超时(大文件传输需要更长时间)
client_body_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
七、常用命令速查
bash
# 测试配置文件语法
nginx -t
# 重新加载配置(不中断服务)
nginx -s reload
# 优雅停止(处理完当前请求后停止)
nginx -s quit
# 立即停止
nginx -s stop
# 查看 Nginx 进程
ps aux | grep nginx
# 查看访问日志(实时)
tail -f /var/log/nginx/access.log
# 查看错误日志
tail -f /var/log/nginx/error.log
# 查看 Nginx 状态(需要 stub_status 模块)
curl http://127.0.0.1/nginx_status
八、总结
Nginx 配置掌握这几个核心场景就够用了:
| 场景 | 关键配置 |
|---|---|
| 前端部署 | try_files $uri /index.html |
| 反向代理 | proxy_pass + proxy_set_header |
| 负载均衡 | upstream + ip_hash/least_conn |
| HTTPS | ssl_certificate + TLSv1.2/1.3 |
| 限流 | limit_req_zone + limit_req |
| 性能 | gzip + expires + sendfile |
💬 运维配置踩过哪些坑?欢迎评论区分享!点赞+收藏,持续更新 Linux/运维实战干货!
标签:Nginx | Linux | 运维 | 反向代理 | HTTPS