varnish 将客户端 IP 地址转发到后端

varnish 将客户端 IP 地址转发到后端

我已将 varnish 设置为代理,以将 HTTP 请求重定向到运行 apache 的后端服务器。我希望在我的 apache 日志中显示客户端 IP 地址,而不是 varnish 服务器 IP 地址。这是我的 varnish 配置文件:

backend $my_backend {
    .host = "192.168.0.103";
    .port = "80";
}
sub vcl_recv {
} else if (req.http.host == "$my_domain_name") {
    set req.backend = $my_backend;
    if (req.request == "POST") {
        if (req.http.X-Forwarded-For) {
          set req.http.X-Real-Forwarded-For = req.http.X-Forwarded-For ", " regsub(client.ip, ":.*", "");
          unset req.http.X-Forwarded-For;
       } else {
          # Simply use the client IP
          set req.http.X-Real-Forwarded-For = regsub(client.ip, ":.*", "");
       }
        return(pipe);
    }
    return(lookup);
}
}

在后端 apache 配置文件中我有这个

RPAFenable On
RPAFsethostname On
RPAFproxy_ips $varnish_proxy_ip
RPAFheader X-Real-IP

问题是指令 RPAFheader 在 Debian6 上无法识别:

root@$hostname:~# apache2ctl configtest
Invalid command 'RPAFheader', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.
root@$hostname:~# 

有没有人已经在 debian 上设置了 mod_rpaf 来帮助我解决这个问题mod_rpaf

非常感谢您的帮助!

答案1

好的,我将回答我自己的问题以帮助可能遇到同样问题的人:

首先在 varnish 配置文件(default.vcl)中添加以下几行

sub vcl_recv {
   if (req.http.host == "myDomain.net") {
       set req.http.host = "myDomain.net";
       set req.backend = myBackend;
       # Compatiblity with Apache log
       remove req.http.X-Forwarded-For;
       set req.http.X-Forwarded-For = client.ip;
       # No cache for POST requests
       if (req.request == "POST") {
           return(pipe);
       }   
       return(lookup);
   }
}

然后在配置 vhost 时为 apache 添加个性化日志格式

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" varnishcombined
 ...
 CustomLog      ${APACHE_LOG_DIR}/access.log varnishcombined

就是这样!

相关内容