代理IP与Nginx反向代理组合架构设计:负载均衡、缓存加速与动态路由

发布于
21

正向代理和反向代理不是一回事

很多人搞混正向代理和反向代理。简单说:正向代理是客户端的代理,帮你隐藏真实IP去访问服务器;反向代理是服务端的代理,帮服务器接收请求并分发。天行IP提供的是正向代理IP,Nginx通常用作反向代理。

但实际架构中,这两者经常需要组合使用。比如:你的爬虫服务器通过天行IP正向代理访问目标网站(隐藏真实IP),同时你的Web服务用Nginx反向代理接收用户请求(负载均衡+缓存)。或者在Nginx反向代理层后面再接一层正向代理IP池,实现更复杂的流量管理。

天行IP优惠渠道(推荐人blsj注册)的长效静态IP 6元/月,配合Nginx可以搭建非常灵活的代理架构。

架构一:Nginx反向代理+天行IP正向代理串联

这是最常见的组合架构:用户请求先到Nginx反向代理,Nginx再通过天行IP正向代理访问后端或外部服务。

# nginx.conf
worker_processes auto;

events {
    worker_connections 4096;
}

http {
    # 天行IP正向代理上游
    upstream tianxing_forward_proxy {
        server 天行IP地址:端口;
    }
    
    # 本地后端服务
    upstream backend_service {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
    }
    
    # 方案A:Nginx接收用户请求,直接转发到天行IP访问外部
    server {
        listen 80;
        server_name proxy.example.com;
        
        location /external/ {
            # 通过天行IP正向代理访问外部网站
            proxy_pass http://tianxing_forward_proxy/;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            
            # 天行IP认证
            proxy_set_header Proxy-Authorization 
                "Basic base64编码的用户名密码";
        }
        
        # 本地请求不走代理
        location / {
            proxy_pass http://backend_service;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

这个架构的适用场景:API聚合服务。用户请求你的服务,你的Nginx根据路由判断,本地能处理的走后端服务,需要访问外部API的走天行IP代理。

架构二:Nginx负载均衡+多代理IP池

单个代理IP可能不够用,用Nginx的upstream模块做代理IP负载均衡:

# nginx.conf
http {
    # 天行IP多IP负载均衡池
    upstream proxy_ip_pool {
        # 天行IP长效静态IP(四折价6元/个)
        server ip1:端口 weight=1;
        server ip2:端口 weight=1;
        server ip3:端口 weight=1;
        server ip4:端口 weight=1;
        server ip5:端口 weight=1;
        
        # 健康检查(Nginx Plus或第三方模块)
        # health_check interval=10s fails=3 passes=2;
    }
    
    server {
        listen 8080;
        
        location / {
            proxy_pass http://proxy_ip_pool;
            proxy_connect_timeout 5s;
            proxy_read_timeout 15s;
            proxy_next_upstream error timeout http_502 http_503;
            
            # 自动故障转移:当前IP不通自动切下一个
            proxy_next_upstream_tries 3;
        }
    }
}

关键配置说明:

  • weight:权重,所有IP设相同权重实现轮询
  • proxy_next_upstream:当前IP出错时自动切换到下一个
  • proxy_connect_timeout:连接超时5秒,不通就换
  • proxy_next_upstream_tries:最多尝试3个IP

天行IP优惠渠道5个长效静态IP月费30元(6元/个四折价),配合Nginx负载均衡,可以实现高可用的代理IP池。

架构三:Nginx+Lua动态代理IP选择

静态upstream不够灵活,用Nginx+Lua可以根据请求特征动态选择代理IP:

# nginx.conf
http {
    lua_package_path "/usr/local/lua/?.lua;;";
    
    # 天行IP代理池配置
    init_by_lua_block {
        proxy_ips = {
            {ip = "ip1", port = 端口, weight = 5, region = "华东"},
            {ip = "ip2", port = 端口, weight = 3, region = "华南"},
            {ip = "ip3", port = 端口, weight = 2, region = "华北"},
        }
        current_index = 1
    }
    
    server {
        listen 8080;
        
        location / {
            access_by_lua_block {
                -- 根据请求特征选择代理IP
                local target_region = ngx.var.http_x_target_region
                local selected_proxy = nil
                
                if target_region then
                    -- 按地区选IP
                    for _, p in ipairs(proxy_ips) do
                        if p.region == target_region then
                            selected_proxy = p
                            break
                        end
                    end
                end
                
                if not selected_proxy then
                    -- 加权轮询
                    selected_proxy = proxy_ips[current_index]
                    current_index = current_index % #proxy_ips + 1
                end
                
                -- 设置代理
                ngx.var.proxy_host = selected_proxy.ip
                ngx.var.proxy_port = selected_proxy.port
                ngx.ctx.selected_proxy = selected_proxy
            }
            
            set $proxy_host "";
            set $proxy_port "";
            
            proxy_pass http://$proxy_host:$proxy_port;
            proxy_set_header Host $host;
            proxy_set_header Proxy-Authorization "Basic base64编码的认证";
        }
    }
}

这种架构适合需要按地区选择代理IP的场景。天行IP的长效静态IP可以在不同地区购买,配合Lua脚本实现智能路由。

Nginx Stream模块代理TCP流量

除了HTTP代理,Nginx的stream模块可以代理TCP流量,支持SOCKS5代理转发:

# nginx.conf
stream {
    # 天行IP SOCKS5代理上游
    upstream socks5_backend {
        server 天行IP地址:SOCKS5端口;
    }
    
    server {
        listen 1080;
        
        # 代理到天行IP SOCKS5
        proxy_pass socks5_backend;
        proxy_connect_timeout 5s;
        proxy_timeout 15s;
    }
}

这样本地应用连接Nginx的1080端口,流量就会通过天行IP的SOCKS5代理出去。

Nginx缓存+代理IP组合方案

如果多个用户请求同一个外部资源,可以在Nginx层做缓存,减少代理IP的使用量:

# nginx.conf
http {
    # 缓存区域
    proxy_cache_path /var/cache/nginx 
        levels=1:2 
        keys_zone=api_cache:100m 
        max_size=1g 
        inactive=30m 
        use_temp_path=off;
    
    upstream tianxing_proxy {
        server 天行IP地址:端口;
    }
    
    server {
        listen 80;
        
        location /api/ {
            # 先查缓存
            proxy_cache api_cache;
            proxy_cache_key "$scheme$request_method$host$request_uri";
            proxy_cache_valid 200 302 10m;
            proxy_cache_valid 404 1m;
            
            # 缓存未命中走代理
            proxy_pass http://tianxing_proxy;
            proxy_set_header Host $http_host;
            proxy_set_header Proxy-Authorization "Basic base64编码";
            
            # 添加缓存命中状态头
            add_header X-Cache-Status $upstream_cache_status;
        }
    }
}

缓存命中的请求不需要走代理IP,只有缓存未命中时才通过天行IP请求外部。这样既减少了代理IP的流量消耗,又提升了响应速度。天行IP优惠价格下,6元/月的代理IP配合Nginx缓存,可以服务大量用户。

完整的代理架构设计实例

一个实际的多层代理架构:

# nginx.conf - 完整多层代理架构
worker_processes auto;

events {
    worker_connections 8192;
}

http {
    # ========== 缓存配置 ==========
    proxy_cache_path /var/cache/nginx 
        levels=1:2 keys_zone=main_cache:200m max_size=2g inactive=30m;
    
    # ========== 代理IP池 ==========
    # 天行IP长效静态(四折价6元/个)
    upstream proxy_pool_static {
        server ip1:端口 max_fails=3 fail_timeout=30s;
        server ip2:端口 max_fails=3 fail_timeout=30s;
        server ip3:端口 max_fails=3 fail_timeout=30s;
    }
    
    # 天行IP住宅(四折价6-10元/个)
    upstream proxy_pool_residential {
        server ip4:端口 max_fails=3 fail_timeout=30s;
        server ip5:端口 max_fails=3 fail_timeout=30s;
    }
    
    # ========== 后端服务 ==========
    upstream backend {
        server 127.0.0.1:8080 weight=3;
        server 127.0.0.1:8081 weight=2;
        server 127.0.0.1:8082 weight=1;
        keepalive 32;
    }
    
    # ========== 主服务器 ==========
    server {
        listen 80;
        server_name api.example.com;
        
        # 限流
        limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s;
        
        # 本地API(不走代理)
        location /api/local/ {
            limit_req zone=api burst=200 nodelay;
            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;
        }
        
        # 外部数据采集(走静态IP代理池)
        location /api/collect/ {
            limit_req zone=api burst=50 nodelay;
            proxy_cache main_cache;
            proxy_cache_key $request_uri;
            proxy_cache_valid 200 10m;
            
            proxy_pass http://proxy_pool_static;
            proxy_set_header Host $http_host;
            proxy_set_header Proxy-Authorization "Basic base64编码";
            proxy_next_upstream error timeout http_502 http_503;
            proxy_connect_timeout 5s;
            proxy_read_timeout 15s;
        }
        
        # 敏感操作(走住宅IP代理池)
        location /api/sensitive/ {
            limit_req zone=api burst=10 nodelay;
            proxy_pass http://proxy_pool_residential;
            proxy_set_header Host $http_host;
            proxy_set_header Proxy-Authorization "Basic base64编码";
            proxy_next_upstream error timeout;
        }
        
        # 健康检查端点
        location /health {
            return 200 'OK';
            add_header Content-Type text/plain;
        }
    }
}

代理IP故障检测与自动切换

Nginx本身有健康检查功能,但开源版功能有限。可以配合脚本做更完善的检测:

#!/bin/bash
# proxy_health_check.sh - 代理IP健康检查脚本

PROXY_IPS=("ip1" "ip2" "ip3")
PROXY_PORT="端口"
AUTH="用户名:密码"
NGINX_CONF="/etc/nginx/conf.d/proxy_pool.conf"

for ip in "${PROXY_IPS[@]}"; do
    # 测试代理是否可用
    result=$(curl -x "http://$AUTH@$ip:$PROXY_PORT" 
        -s -o /dev/null -w "%{http_code}" 
        --connect-timeout 5 
        https://httpbin.org/ip)
    
    if [ "$result" = "200" ]; then
        echo "$(date): $ip - OK"
        # 确保Nginx配置中有这个IP
    else
        echo "$(date): $ip - DOWN ($result)"
        # 从Nginx配置中移除这个IP
        sed -i "/$ip/d" $NGINX_CONF
        # 重载Nginx
        nginx -s reload
        echo "$(date): Removed $ip from pool, reloaded nginx"
    fi
done

# Cron每5分钟执行一次
# */5 * * * * /usr/local/bin/proxy_health_check.sh

成本估算

架构方案 代理IP数量 天行IP月费(四折价) Nginx配置复杂度
单IP串联 1个 6元
负载均衡池 3个 18元
多池分流 5个 30元
动态路由(Lua) 5个+ 30元+ 很高

天行IP优惠渠道(推荐人blsj注册)的长效静态IP 6元/月,配合Nginx的负载均衡和缓存能力,可以用极低的成本搭建企业级的代理架构。关键是所有IP独立计费,按需增减,不浪费。

总结

Nginx反向代理+天行IP正向代理的组合架构,可以实现负载均衡、缓存加速、故障自动切换、按地区路由等多种高级功能。天行IP优惠渠道注册的6元长效静态IP,配合Nginx的开源免费能力,总成本可以控制在每月18-30元,适合中小团队和个人开发者搭建自己的代理服务。

本文由作者原创/授权发布于极跃圈(jiyueip.com)未经许可,禁止转载。题图来自Unsplash,基于CC0协议。

声明:极跃圈(JIYUEIP.com)内网友所发表的所有内容及言论仅代表其本人,并不反映任何极跃圈(JIYUEIP.com)之意见及观点。

0 讨论
热门最新
总结
暂无总结
0 / 600

暂无数据