Nginx 反向代理与负载均衡配置实战
一、概述
Nginx 作为高性能的 HTTP 和反向代理服务器,在现代运维架构中扮演着核心角色。本文详细介绍 Nginx 反向代理和负载均衡的配置方法与最佳实践。
二、基础概念
2.1 反向代理 vs 正向代理
| 类型 |
代理对象 |
客户端感知 |
典型场景 |
| 正向代理 |
客户端 |
服务器知道代理存在 |
翻墙、内网访问外网 |
| 反向代理 |
服务器 |
客户端不知道代理存在 |
负载均衡、SSL 终止 |
2.2 负载均衡算法
- round_robin(默认):轮询分发
- least_conn:最少连接优先
- ip_hash:源 IP 哈希保持会话
- weight:权重分配
三、安装与基础配置
3.1 安装 Nginx
1 2 3 4 5 6 7 8 9
| sudo apt update sudo apt install nginx -y
sudo yum install nginx -y
nginx -v
|
3.2 目录结构
1 2 3 4 5
| /etc/nginx/ ├── nginx.conf # 主配置文件 ├── conf.d/ # 额外配置目录 ├── sites-available/ # 可用站点配置 └── sites-enabled/ # 已启用站点配置(软链接)
|
四、反向代理配置
4.1 基础反向代理
1 2 3 4 5 6 7 8 9 10 11 12
| server { listen 80; server_name example.com;
location / { proxy_pass http://127.0.0.1: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; } }
|
4.2 常用代理参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| location / { proxy_pass http://backend; proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; proxy_next_upstream_tries 3; }
|
五、负载均衡配置
5.1 基础负载均衡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12: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; } }
|
5.2 加权轮询
1 2 3 4 5
| upstream backend { server 192.168.1.10:8080 weight=3; server 192.168.1.11:8080 weight=2; server 192.168.1.12:8080 weight=1; }
|
5.3 最少连接算法
1 2 3 4 5 6
| upstream backend { least_conn; server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }
|
5.4 IP 哈希会话保持
1 2 3 4 5 6
| upstream backend { ip_hash; server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }
|
5.5 备用服务器配置
1 2 3 4 5
| upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080 backup; }
|
5.6 健康检查配置
1 2 3 4 5
| upstream backend { server 192.168.1.10:8080 max_fails=3 fail_timeout=30s; server 192.168.1.11:8080 max_fails=3 fail_timeout=30s; server 192.168.1.12:8080 max_fails=3 fail_timeout=30s; }
|
六、HTTPS 配置
6.1 SSL 证书配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| 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_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; 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; } }
server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; }
|
七、性能优化
7.1 开启 Gzip 压缩
1 2 3 4 5 6 7 8
| http { gzip on; gzip_vary on; gzip_min_length 1024; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/javascript; gzip_disable "MSIE [1-6]\."; }
|
7.2 静态文件缓存
1 2 3 4 5
| location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, immutable"; access_log off; }
|
7.3 连接优化
1 2 3 4 5 6 7 8 9 10 11 12 13
| events { worker_connections 65535; use epoll; multi_accept on; }
http { keepalive_timeout 65; keepalive_requests 100; sendfile on; tcp_nopush on; tcp_nodelay on; }
|
八、监控与日志
8.1 访问日志格式
1 2 3 4 5 6 7
| log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' 'rt=$request_time uct="$upstream_connect_time" ' 'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log main;
|
8.2 错误日志
1
| error_log /var/log/nginx/error.log warn;
|
8.3 状态监控
1 2 3 4 5 6 7 8 9 10 11
| server { listen 8080; server_name localhost;
location /nginx_status { stub_status on; allow 127.0.0.1; allow 192.168.1.0/24; deny all; } }
|
九、常见问题排查
9.1 配置测试
1 2 3 4 5 6 7 8
| nginx -t
nginx -s reload
systemctl status nginx
|
9.2 常见错误
| 错误 |
可能原因 |
解决方案 |
| 502 Bad Gateway |
后端服务不可用 |
检查后端服务状态 |
| 504 Gateway Timeout |
后端响应超时 |
增加 proxy_read_timeout |
| 413 Request Entity Too Large |
请求体过大 |
增加 client_max_body_size |
| 503 Service Unavailable |
所有后端不可用 |
检查 upstream 配置 |
十、安全加固
10.1 隐藏 Nginx 版本
1 2 3
| http { server_tokens off; }
|
10.2 限制请求频率
1 2 3 4 5 6 7 8 9
| http { limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; server { location / { limit_req zone=one burst=20 nodelay; } } }
|
10.3 限制并发连接
1 2 3 4 5 6 7 8 9
| http { limit_conn_zone $binary_remote_addr zone=addr:10m; server { location / { limit_conn addr 10; } } }
|
十一、总结
Nginx 反向代理和负载均衡是构建高可用、高性能 Web 架构的核心技术。合理配置可以显著提升系统稳定性和用户体验。建议在生产环境部署前充分测试,并建立完善的监控告警机制。