通过nginx实现七层正向代理


背景描述

当我们源站只在一个地区,但 边缘用户/CDN 直接回源因为公网不确定因素导致回源不稳定的时候,这时我们需要考虑如何让 “源站” 更贴近用户;

于是可以在异地设置一个边缘节点,然后通过专线或相较公网更稳定的方式回源,于是有了如下设置。


代理设置

  • 简略配置如下

    upstream source_server {
        # 可选ip_hash,保障客户端原进原出
        ip_hash;
        server 10.20.30.40:80;
        server 172.17.50.60:80;
        keepalive 30;
    }
    
    server {
        listen    80;
        listen    443 ssl http2;
        server_name ~^.*\.nestealin\.com$;
        charset utf-8;
        access_log  logs/$host.access.main.log main;
        error_log  logs/all.nestealin.com.error.crit.log crit;
    
        ssl_certificate      /data/keys/server.cer;
        ssl_certificate_key  /data/keys/server.key;
        ssl_session_cache shared:SSL:30m;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ecdh_curve X25519:P-256:P-384;
        ssl_ciphers TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:TLS13-AES-128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-CHACHA20-POLY1305:EECDH+CHACHA20:EECDH+AES128;
    
        location / {
            proxy_next_upstream error timeout http_503 http_504 http_502;
            proxy_redirect off;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $clientRealIp;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-Port $remote_port;
            proxy_connect_timeout 120s;
            proxy_read_timeout 600s;
            proxy_send_timeout 600s;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_pass http://source_server;
        }
    
    }
    
  • 以上,即可实现边缘节点 泛域名 接收请求,并将请求转给后端源站服务器。


举一反三: 正向代理

  • 同样地,也可以通过 nginx 做一个正向代理工具,例如代理请求 baidu.com

    server {
        listen    80;
        listen    443 ssl http2;
        server_name ~^.*\.nestealin\.com$;
        charset utf-8;
        access_log  logs/$host.access.main.log main;
        error_log  logs/all.nestealin.com.error.crit.log crit;
    
        ssl_certificate      /data/keys/server.cer;
        ssl_certificate_key  /data/keys/server.key;
        ssl_session_cache shared:SSL:30m;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ecdh_curve X25519:P-256:P-384;
        ssl_ciphers TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:TLS13-AES-128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-CHACHA20-POLY1305:EECDH+CHACHA20:EECDH+AES128;
    
        location ~* ^/prx/locate/web01 {
            resolver 119.29.29.29;
            resolver_timeout 60s;
            # 改写URI地址
            rewrite  ^(.*)$  /locate/web01 break;
            proxy_pass https://www.baidu.com;
        }
    
    }

文章作者: NesTeaLin
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 NesTeaLin !
  目录