Nginx反向代理与负载均衡配置实战指南
前言
Nginx作为高性能的Web服务器和反向代理服务器,在现代Web架构中扮演着至关重要的角色。本文将从基础配置到高级应用,详细讲解Nginx反向代理与负载均衡的实战配置技巧,帮助你构建高可用、高性能的服务架构。
一、Nginx反向代理基础
1.1 什么是反向代理
反向代理(Reverse Proxy)是指代理服务器接收客户端的请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给客户端。
反向代理的优势:
- 隐藏后端服务器真实IP
- 负载均衡,分发请求
- 统一入口,便于管理
- SSL终端,集中证书管理
- 缓存静态内容,减轻后端压力
- 安全防护,WAF接入
1.2 基础反向代理配置
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;
}
}1.3 常用代理参数详解
# 连接超时时间
proxy_connect_timeout 60s;
# 发送超时时间
proxy_send_timeout 60s;
# 读取超时时间
proxy_read_timeout 60s;
# 代理缓冲区
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
# 重定向设置
proxy_redirect off;
# 支持大文件上传
client_max_body_size 100m;二、负载均衡配置
2.1 负载均衡策略
Nginx提供多种负载均衡策略:
1. 轮询(默认)
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}2. 权重(weight)
upstream backend {
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080 weight=2;
server 192.168.1.103:8080 weight=1;
}3. IP哈希(ip_hash)
upstream backend {
ip_hash;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}4. 最少连接(least_conn)
upstream backend {
least_conn;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}5. 公平(fair)- 需要第三方模块
upstream backend {
fair;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}2.2 服务器状态参数
upstream backend {
# 正常服务
server 192.168.1.101:8080;
# 备份服务器,其他都宕机才启用
server 192.168.1.102:8080 backup;
# 标记宕机,不参与负载
server 192.168.1.103:8080 down;
# 最大失败次数
server 192.168.1.104:8080 max_fails=3 fail_timeout=30s;
}三、健康检查配置
3.1 被动健康检查
Nginx自带被动健康检查:
upstream backend {
server 192.168.1.101:8080 max_fails=2 fail_timeout=30s;
server 192.168.1.102:8080 max_fails=2 fail_timeout=30s;
}3.2 主动健康检查(nginx_upstream_check_module)
需要编译安装模块:
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
check interval=3000 rise=2 fall=3 timeout=1000 type=http;
check_http_send "GET /health HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}四、HTTPS反向代理配置
4.1 SSL终端配置
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-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
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-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
# HTTP重定向到HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}五、缓存配置
5.1 静态资源缓存
# 缓存路径配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_valid 200 302 1h;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
add_header X-Cache-Status $upstream_cache_status;
}
}5.2 浏览器缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}六、高级配置技巧
6.1 动静分离
server {
# 静态资源直接返回
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|ttf)$ {
root /var/www/static;
expires 30d;
}
# 动态请求转发到后端
location / {
proxy_pass http://backend;
}
}6.2 路径重写
location /api/ {
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://backend;
}6.3 限流配置
# 限制请求速率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=20 nodelay;
proxy_pass http://backend;
}
}
# 限制连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location / {
limit_conn addr 10;
proxy_pass http://backend;
}
}七、完整配置示例
# 全局配置
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 65535;
multi_accept on;
}
http {
include 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"';
# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss;
# 上游服务器
upstream backend {
least_conn;
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;
}
# HTTP服务器
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
# HTTPS服务器
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;
location / {
proxy_pass http://backend;
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 https;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /var/www/static;
expires 30d;
}
}
}八、性能调优
8.1 Worker进程优化
# CPU核心数
worker_processes auto;
# 绑定CPU核心
worker_cpu_affinity auto;8.2 连接数优化
worker_rlimit_nofile 65535;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}8.3 Buffer优化
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
client_max_body_size 100m;九、常见问题排查
9.1 502 Bad Gateway
- 后端服务未启动
- 防火墙拦截
- SELinux限制
- 端口被占用
9.2 504 Gateway Timeout
- 后端响应太慢
- 超时时间设置过短
- 网络延迟高
9.3 499错误
- 客户端主动断开连接
- 通常是正常现象
十、监控与维护
10.1 Nginx状态监控
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}10.2 日志分析
# 访问TOP 10 IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10
# 状态码统计
awk '{print $9}' access.log | sort | uniq -c | sort -rn结语
Nginx的反向代理和负载均衡功能强大而灵活,是构建现代Web架构不可或缺的组件。掌握这些配置技巧,你就能构建出高性能、高可用的服务架构。记住:配置不是一成不变的,需要根据实际业务场景不断调优。
配置完成后,别忘了使用 nginx -t 测试配置,然后 nginx -s reload 平滑重载。