如何在使用 apache2 作为 tomcat8 的代理时保留客户端 ip

How to preserve client ip while using apache2 as proxy to tomcat8

我有一个 Apache2 服务器,除了在 localhost:8080 的 Tomcat8 服务器上托管一些将 https 转换为 http 的其他内容外,它是 运行 一个 spring-boot 应用程序。为此,我们在 sites-available

中使用以下配置
    ProxyPass / http://0.0.0.0:8080/
    ProxyPassReverse / http://0.0.0.0:8080/

这一切都为我们所用。直到我们观察到由于我们错过的一个明显原因而无法记录客户端 IP。由于我们的请求现在由 apache2 代理,我们收到 127.0.0.1 作为我们的客户端 ip。现在我们如何确保我们收到有效的客户端 ip,就像之前我们没有使用 apache2 作为代理服务器时的情况一样。

提前致谢。

该问题的解决方案要求代理在转发前在请求的X-Forwarded-For Header 中保留主机信息。在 Apache2 中,这是通过添加

来实现的
ProxyPreserveHost On

以及相应 VirtualHost 配置的 conf 中的其他信息。可以通过在日志中添加 X-Forwarded-For Header 来验证此实现。在 Apache2 中,您必须按照此处所述为 LogFormat 编辑 /etc/apache2/apache2.conf

How can I configure my Apache server to log my client's public IP addresses

观察 /var/log/apache2/access.log 处的日志 X-Forwarded-For header。

一旦您确信这一点,您现在可以配置 Tomcat8 以在 /etc/tomcat8/server.xml 中配置一个阀,如描述的那样 here:

或简单地添加:

   <Valve className="org.apache.catalina.valves.RemoteIpValve"  internalProxies="127.0.0.1" remoteIpHeader="x-forwarded-for" />

希望对其他人有所帮助