Make Tomcat use X-Real-IP

Solution 1:

It's required to add Valve in Tomcat configuration:

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

After that Tomcat starts to dispatch headers passed from nginx:

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

Solution 2:

Found this question via google, and want to add comment to the approved answer:

According to documentation, by default this valve (RemoteIpValve) has no effect on the values that are written into access log. In order to get real IPs in log, you should add

requestAttributesEnabled="true"

to AccessLogValve also.

Solution 3:

Another useful example of Tomcat config: internalProxies can be separated with pipeline (|) since accepts regular expression.

<Valve
   className="org.apache.catalina.valves.RemoteIpValve"
   internalProxies="192\.168\.10\.110|127\.0\.0\.1"
   remoteIpHeader="x-forwarded-for"
   proxiesHeader="x-forwarded-by"
   protocolHeader="x-forwarded-proto"
   />

For more examples refer to tomcat document

Solution 4:

I was searching for the same thing and found information leading me to the following solution from researching around the net.

In your tomcat server.xml you need to edit the logging valve pattern to get the values from the incoming header.

In your

and change the pattern to:

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; ] "

My full access log value looks like the following:

      <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; ] " />

This is accompanied by the Nginx config of:

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;
}

Additional information of log valve patterns in Tomcat can be found at: Apache 7: The Valve Component