正向代理: - 客户端明确配置的代理服务器 - 代表客户端向互联网请求资源 - 主要用途:突破访问限制、匿名访问、缓存加速
反向代理: - 客户端无感知的代理架构 - 代表服务器接收和处理请求 - 主要用途:负载均衡、安全防护、高可用性
客户端请求 → Nginx监听端口 → 反向代理模块处理 → 上游服务器选择 → 请求转发 → 响应返回
http {
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com;
server backup.example.com backup;
}
server {
listen 80;
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_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 24k;
超时控制:
proxy_connect_timeout 5s;
proxy_send_timeout 10s;
proxy_read_timeout 30s;
缓存配置:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";
upstream backend {
server 10.0.0.1:8080;
keepalive 32; # 保持的连接数
}
server {
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://backend;
}
}
upstream backend {
zone backend 64k;
server 10.0.0.1:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.2:8080 max_fails=3 fail_timeout=30s;
# 商业版才支持主动健康检查
# health_check interval=5s uri=/health_check;
}
server {
# 隐藏服务器信息
server_tokens off;
# 限制HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 防止Host头攻击
if ($host !~* ^(example.com|www.example.com)$ ) {
return 444;
}
}
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://api_backend;
}
upstream auth_service {
server 10.0.1.10:8000;
}
upstream order_service {
server 10.0.1.20:8000;
}
server {
location /auth/ {
rewrite ^/auth/(.*) /$1 break;
proxy_pass http://auth_service;
}
location /orders/ {
rewrite ^/orders/(.*) /$1 break;
proxy_pass http://order_service;
}
}
location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400; # 保持长连接
}
server {
location /static/ {
root /var/www/static;
expires 30d;
access_log off;
}
location / {
proxy_pass http://dynamic_backend;
}
}
ngx_http_stub_status_module
$request_time
日志分析502 Bad Gateway
性能瓶颈
缓存不生效
proxy_cache_key
配置# 使用Nginx Plus或OpenResty
upstream backend {
zone backend 64k;
server 10.0.0.1:8080 resolve;
server 10.0.0.2:8080 resolve;
}
# 作为Istio Ingress Gateway的替代方案
location / {
proxy_pass http://istio-ingressgateway.istio-system.svc.cluster.local;
# 携带必要的Istio头信息
proxy_set_header X-Request-ID $request_id;
}
# 边缘节点缓存策略
proxy_cache_lock on;
proxy_cache_use_stale updating error timeout invalid_header;
proxy_cache_background_update on;
通过以上深入解析,可以看出Nginx反向代理不仅是一个简单的请求转发工具,而是现代分布式系统中不可或缺的基础设施组件,合理配置和优化可以显著提升系统整体的性能、可靠性和安全性。