使Tomcat使用X-Real-IP

我将nginxconfiguration为Tomcat 7之前的反向代理。我将以下几行添加到了nginxconfiguration中:

set_real_ip_from 127.0.0.1; ... location / { proxy_pass http://tomcat; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } 

但是,我仍然在Tomcat中看到以下图片:

 127.0.0.1 - - [10/Jun/2013:11:25:48 +0600] "GET /app/welcome;jsessionid=6C1B02376C5F748C509B28FC7CE416C9 HTTP/1.0" 200 10571 127.0.0.1 - - [10/Jun/2013:11:25:48 +0600] "GET /app/welcome;jsessionid=0BBE0174C1F0E94FDF49610144E809D3 HTTP/1.0" 200 10571 127.0.0.1 - - [10/Jun/2013:11:25:48 +0600] "GET /app/welcome;jsessionid=AD48005AD453F3A0BE46F1AC978F145D HTTP/1.0" 200 10571 

有没有办法强制Tomcat使用X-Real-IP头(并将其写入日志文件), 而无需修改 Web应用程序?

需要在Tomcatconfiguration中添加Valve:

 <Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="X-Forwarded-For" requestAttributesEnabled="true" internalProxies="127\.0\.0\.1" /> 

之后,Tomcat开始调度从nginx传递的头文件:

 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

我正在寻找相同的东西,发现信息引导我从网上search下面的解决scheme。

在您的tomcat server.xml中,您需要编辑日志阀模式以获取传入标题中的值。

在你的

并将模式更改为:

 pattern="Remote User[ %{X-Forwarded-For}i %l %u %t ] Request[ &quot;%r&quot; ] Status Code[ %s ] Bytes[ %b ] Referer[ &quot;%{Referer}i&quot; ] Agent[ &quot;%{User-agent}i&quot; ] " 

我的完整访问日志值如下所示:

  <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="access_log." suffix=".txt" pattern="Remote User[ %{X-Forwarded-For}i %l %u %t ] Request[ &quot;%r&quot; ] Status Code[ %s ] Bytes[ %b ] Referer[ &quot;%{Referer}i&quot; ] Agent[ &quot;%{User-agent}i&quot; ] " /> 

这是伴随着Nginx的configuration:

 location / { proxy_pass http://localhost:8080; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_intercept_errors on; } 

有关Tomcat中对数阀模式的更多信息,请参阅: Apache 7:阀组件

通过谷歌发现这个问题,并希望添加评论的核准答案:

根据文档 ,默认情况下,此阀(RemoteIpValve)对写入访问日志的值没有影响。 为了获得真正的IP日志,你应该添加

 requestAttributesEnabled="true" 

到AccessLogValve也。