以下是Nginx反向代理的最佳设置方案,涵盖基础配置、性能优化及安全增强:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_server; # 后端服务器地址
proxy_set_header Host $host; # 传递原始域名
proxy_set_header X-Real-IP $remote_addr; # 传递客户端真实IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 记录请求链路IP
}
}
关键参数说明:
proxy_pass
:指向后端服务地址,支持HTTP/HTTPS协议。proxy_set_header
:确保后端获取正确请求头,如Host
用于虚拟主机识别。upstream backend {
least_conn; # 按连接数最少分配(推荐高并发场景)
server 192.168.1.1:8080 weight=3; # 权重3,处理更多请求
server 192.168.1.2:8080;
server 192.168.1.3:8080 backup; # 备用服务器,主服务器故障时启用
proxy_next_upstream error timeout http_500; # 故障转移条件
}
server {
location / {
proxy_pass http://backend;
}
}
负载均衡算法:
round-robin
(默认):轮询分配请求。ip_hash
:基于客户端IP哈希,保证会话保持(如登录状态)。proxy_connect_timeout 5s; # 连接后端超时时间
proxy_read_timeout 30s; # 读取响应超时时间
proxy_send_timeout 30s; # 发送请求超时时间
client_max_body_size 100m; # 允许最大请求体大小(如文件上传)
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g;
location /static/ {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m; # 缓存200/302状态码10分钟
proxy_cache_valid 404 1m; # 缓存404状态码1分钟
}
gzip on;
gzip_types text/css application/javascript;
gzip_min_length 1024; # 仅压缩大于1KB的响应
# 限制请求方法(仅允许GET/POST)
location /api/ {
if ($request_method !~ ^(GET|POST)$) {
return 405;
}
}
# 防止SQL注入/XSS(简单示例,建议结合WAF)
if ($query_string ~* "union|select|drop") {
return 403;
}
server_tokens off; # 关闭版本号显示
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256;
}
location /ws/ {
proxy_pass http://backend_websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
proxy_pass
指向IP代理接口,并启用IP轮换:location / {
proxy_pass http://gateway.ipipgo.io:10808;
proxy_set_header X-Real-IP $remote_addr;
# 启用IP心跳检测(需服务商支持)
proxy_next_upstream error timeout;
}
sudo nginx -t # 测试配置是否正确
sudo systemctl reload nginx # 重新加载配置
tail -f /var/log/nginx/access.log
curl
验证代理效果:curl -x http://localhost:80 http://example.com
least_conn
算法,增加worker_connections
和proxy_buffers
。参考来源: