spring-bootapache2ubuntu-16.04tomcat8

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


I have an Apache2 server which is apart from hosting some other content translating https to http on Tomcat8 server at localhost:8080, which is running a spring-boot application. for that we are using below configuratin in sites-available

    ProxyPass / http://0.0.0.0:8080/
    ProxyPassReverse / http://0.0.0.0:8080/

and its all working for us. Until we observe we are unable to log client IP for one obvious reason we missed. since our requests are now proxy by apache2, we are receiving 127.0.0.1 as our client ip. Now how can we ensure we are receiving the valid client ip as was the case earlier when we were not using apache2 as proxy server.

Thanks in advance.


Solution

  • Solution of the problem requires Proxy to Preserve host information in X-Forwarded-For Header of the request before forwarding. In Apache2 this is achieved by adding

    ProxyPreserveHost On
    

    along with other information in conf for the corresponding VirtualHost configuration. Implementation of this can be verified by adding X-Forwarded-For Header in log. In Apache2 you have to edit /etc/apache2/apache2.conf for LogFormat as describe here:

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

    Observe the log at /var/log/apache2/access.log for X-Forwarded-For header.

    Once you are sure of this you can now configure Tomcat8 to configure a valve in /etc/tomcat8/server.xml as describe here:

    or simply add:

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

    I hope this will be helpful for others