Nginx反向代理与负载均衡实战指南
本文详解Nginx反向代理原理、配置技巧和负载均衡策略,从入门到生产级实践。
前言
Nginx是最流行的Web服务器和反向代理:
- 全球使用率超过30%
- 性能强悍,10万+并发轻松
- 配置灵活,功能丰富
今天来深入讲解Nginx反向代理和负载均衡的实战配置。
一、反向代理基础
1.1 什么是反向代理
正向代理(代理客户端):
客户端 → 代理服务器 → 目标服务器
例如:翻墙工具
反向代理(代理服务端):
客户端 → Nginx → 后端服务器
例如:网站负载均衡
1.2 反向代理的作用
| 功能 | 说明 |
|---|---|
| 负载均衡 | 分发请求到多台后端 |
| SSL终结 | 统一处理HTTPS |
| 缓存加速 | 缓存静态资源 |
| 安全隔离 | 隐藏真实服务器 |
| 统一入口 | 多服务共用80/443端口 |
1.3 安装Nginx
bash
# Ubuntu/Debian
sudo apt update
sudo apt install nginx -y
# CentOS
sudo yum install epel-release -y
sudo yum install nginx -y
# 启动
sudo systemctl start nginx
sudo systemctl enable nginx
# 验证
curl http://localhost
二、基础反向代理配置
2.1 最简配置
nginx
# /etc/nginx/conf.d/proxy.conf
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
2.2 完整配置模板
nginx
server {
listen 80;
server_name example.com;
# 日志
access_log /var/log/nginx/example_access.log;
error_log /var/log/nginx/example_error.log;
location / {
proxy_pass http://127.0.0.1:8080;
# 传递真实IP
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;
# 缓冲设置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
}
2.3 多服务代理
nginx
# 不同路径代理到不同服务
server {
listen 80;
server_name example.com;
# 前端静态文件
location / {
root /var/www/html;
try_files $uri $uri/ /index.html;
}
# API服务
location /api/ {
proxy_pass http://127.0.0.1:3000/;
}
# 管理后台
location /admin/ {
proxy_pass http://127.0.0.1:8000/;
}
# WebSocket
location /ws/ {
proxy_pass http://127.0.0.1:9000/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
三、负载均衡
3.1 负载均衡策略
| 策略 | 说明 | 适用场景 |
|---|---|---|
| 轮询(默认) | 依次分发 | 服务器配置相同 |
| 加权轮询 | 按权重分发 | 服务器配置不同 |
| IP Hash | 同IP固定后端 | 需要会话保持 |
| Least Conn | 最少连接优先 | 长连接场景 |
| Fair | 响应时间优先 | 需要第三方模块 |
3.2 轮询配置
nginx
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
3.3 加权轮询
nginx
upstream backend {
server 192.168.1.101:8080 weight=5; # 处理50%请求
server 192.168.1.102:8080 weight=3; # 处理30%请求
server 192.168.1.103:8080 weight=2; # 处理20%请求
}
3.4 IP Hash(会话保持)
nginx
upstream backend {
ip_hash;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}
3.5 最少连接
nginx
upstream backend {
least_conn;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}
3.6 健康检查
nginx
upstream backend {
server 192.168.1.101:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.102:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.103:8080 backup; # 备用服务器
}
# max_fails: 失败次数阈值
# fail_timeout: 标记不可用时长
# backup: 主服务器都挂了才启用
四、HTTPS配置
4.1 SSL证书配置
nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
# SSL优化
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto https;
}
}
# HTTP跳转HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
4.2 Let's Encrypt自动证书
bash
# 安装certbot
sudo apt install certbot python3-certbot-nginx -y
# 自动配置
sudo certbot --nginx -d example.com
# 自动续期
sudo certbot renew --dry-run
五、性能优化
5.1 Gzip压缩
nginx
http {
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript
text/xml application/xml application/xml+rss text/javascript;
}
5.2 静态文件缓存
nginx
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
5.3 代理缓存
nginx
http {
# 定义缓存区
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
max_size=1g inactive=60m use_temp_path=off;
}
server {
location / {
proxy_pass http://backend;
# 启用缓存
proxy_cache my_cache;
proxy_cache_valid 200 60m;
proxy_cache_valid 404 1m;
proxy_cache_key "$scheme$request_method$host$request_uri";
# 缓存状态头
add_header X-Cache-Status $upstream_cache_status;
}
}
5.4 连接优化
nginx
http {
# 长连接
keepalive_timeout 65;
keepalive_requests 1000;
# upstream长连接
upstream backend {
server 127.0.0.1:8080;
keepalive 32;
}
}
六、跨网络代理场景
6.1 常见场景
场景:公司有多个机房/分支,需要统一入口
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 总部机房 │ │ 分部A │ │ 分部B │
│ Nginx │ │ 后端服务 │ │ 后端服务 │
│ 192.168.1.1│ │192.168.2.10│ │192.168.3.10│
└─────────────┘ └─────────────┘ └─────────────┘
问题:各机房网络不通,Nginx无法直接代理到分部服务器。
6.2 组网解决方案
使用组网软件(如星空组网)打通网络:
组网后:
┌─────────────┐
│ Nginx │
│ 10.10.0.1 │←─┐
└─────────────┘ │
│ 组网虚拟局域网
┌─────────────┐ │
│ 分部A │←─┤
│ 10.10.0.2 │ │
└─────────────┘ │
│
┌─────────────┐ │
│ 分部B │←─┘
│ 10.10.0.3 │
└─────────────┘
Nginx配置:
nginx
upstream all_servers {
server 10.10.0.1:8080; # 总部(组网IP)
server 10.10.0.2:8080; # 分部A(组网IP)
server 10.10.0.3:8080; # 分部B(组网IP)
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://all_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
效果:
- 多机房服务统一入口
- 负载均衡跨机房
- 故障自动切换
- 无需公网暴露各分部服务
6.3 按地域分流
nginx
# 根据用户IP分流到最近机房
upstream beijing {
server 10.10.0.1:8080;
}
upstream shanghai {
server 10.10.0.2:8080;
}
upstream guangzhou {
server 10.10.0.3:8080;
}
# 需要GeoIP模块
map $geoip_city $backend {
default beijing;
"Shanghai" shanghai;
"Guangzhou" guangzhou;
}
server {
location / {
proxy_pass http://$backend;
}
}
七、安全配置
7.1 限流
nginx
http {
# 定义限流区
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
}
server {
location /api/ {
# 每秒10个请求,突发20个
limit_req zone=one burst=20 nodelay;
# 每IP最多100连接
limit_conn addr 100;
proxy_pass http://backend;
}
}
7.2 访问控制
nginx
location /admin/ {
# 白名单
allow 192.168.1.0/24;
allow 10.10.0.0/24; # 组网IP段
deny all;
proxy_pass http://backend;
}
7.3 隐藏版本信息
nginx
http {
server_tokens off;
}
7.4 防盗链
nginx
location ~* \.(gif|jpg|png)$ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}
八、监控与日志
8.1 自定义日志格式
nginx
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$upstream_addr $upstream_response_time $request_time';
access_log /var/log/nginx/access.log main;
}
8.2 状态监控
nginx
server {
listen 8080;
location /nginx_status {
stub_status on;
allow 127.0.0.1;
allow 10.10.0.0/24; # 组网IP
deny all;
}
}
bash
# 查看状态
curl http://localhost:8080/nginx_status
Active connections: 42
server accepts handled requests
7368 7368 12345
Reading: 0 Writing: 5 Waiting: 37
8.3 日志分析
bash
# 统计请求数
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20
# 统计状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 慢请求分析
awk '$NF > 1 {print $0}' access.log
九、常见问题
9.1 502 Bad Gateway
bash
# 后端服务未启动或无法连接
# 检查后端服务
curl http://127.0.0.1:8080
# 检查Nginx错误日志
tail -f /var/log/nginx/error.log
9.2 504 Gateway Timeout
nginx
# 增加超时时间
location / {
proxy_pass http://backend;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
9.3 配置检查
bash
# 检查配置语法
nginx -t
# 重载配置
nginx -s reload
十、总结
Nginx反向代理配置要点:
- 基础代理:proxy_pass + 必要的header
- 负载均衡:根据场景选择策略
- 健康检查:设置失败阈值和备用服务器
- HTTPS:Let's Encrypt免费证书
- 性能优化:Gzip、缓存、长连接
- 跨网络代理:组网打通多机房
- 安全加固:限流、访问控制
生产环境建议:
- 配置健康检查
- 启用访问日志
- 配置合理的超时
- 使用HTTPS
参考资料
- Nginx官方文档:https://nginx.org/en/docs/
- Nginx负载均衡:https://docs.nginx.com/nginx/admin-guide/load-balancer/
💡 建议:先在测试环境验证配置,再应用到生产。改配置前记得备份。