日常工作中,使用haproxy进行负载调度,后端的webserver需要记录真实的客户端地址,所以需要在haproxy上和后端的webserver上进行针对性的配置。
使用haproxy+Nginx实现IP的透传
Nginx的配置:(日志格式需要修改,)

http {
log_format access_json '{"@timestamp":"$time_iso8601",'
'"host":"$server_addr",'
'"clientip":"$remote_addr",'
'"size":$body_bytes_sent,'
'"responsetime":$request_time,'
'"upstreamtime":"$upstream_response_time",'
'"upstreamhost":"$upstream_addr",'
'"http_host":"$host",'
'"uri":"$uri",'
'"domain":"$host",'
'"xff":"$http_x_forwarded_for",'
'"referer":"$http_referer",'
'"tcp_xff":"$proxy_protocol_addr",'
'"http_user_agent":"$http_user_agent",'
'"status":"$status"}';
    access_log /var/log/nginx/access_json.log access_json;
}

1、七层代理的IP透传
haproxy配置(模式为http)

listen web_server
        bind 192.168.43.102:80
        mode http
        option forwardfor
        server web1 192.168.43.103:80 check inter 3s fall 3 rise 5

nginx中日志:(xff字段显示实际的客户端地址)

[root@centos7 nginx]# tail -f access_json.log 
{"@timestamp":"2022-09-11T19:05:35+08:00","host":"192.168.43.103","clientip":"192.168.43.102","size":4833,"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-","http_host":"192.168.43.102","uri":"/index.html","domain":"192.168.43.102","xff":"192.168.43.101","referer":"-","tcp_xff":"-","http_user_agent":"curl/7.29.0","status":"200"}

2、四层代理的IP透传
haproxy配置(模式要修改为tcp)

listen web_server
        bind 192.168.43.102:80
        mode tcp
        option forwardfor
        server web1 192.168.43.103:80 send-proxy check inter 3s fall 3 rise 5

Nginx中的配置:

 server {
        listen 80 proxy_protocol;

‘“tcp_xff”:”$proxy_protocol_addr”,’(日志格式)
Nginx中的日志:(tcp_xff字段就是客户端地址)

{"@timestamp":"2022-09-11T19:13:05+08:00","host":"192.168.43.103","clientip":"192.168.43.102","size":4833,"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-","http_host":"192.168.43.102","uri":"/index.html","domain":"192.168.43.102","xff":"-","referer":"-","tcp_xff":"192.168.43.101","http_user_agent":"curl/7.29.0","status":"200"}
文档更新时间: 2023-08-17 06:43   作者:月影鹏鹏
IT运维支持-AIWALY-月影工作室