Tuesday, November 29, 2016

Tracking the Web Requests' originating IP addresses and ports

My web app tracks requests to our site, and part of the tracking include the request's originating IP address, port, among other things.

With PHP, I rely on the header information, particularly REMOTE_ADDR and REMOTE_PORT, however it does not work after I put the HAProxy in front of the actual web servers, in which case the two values will always be the HAProxy's IP and port. After searching over the web, I found this article that solved the problem:

http://serverfault.com/questions/331079/haproxy-and-forwarding-client-ip-address-to-servers?newreg=2c7b9906767e46d1acf1bdb038253ffd

Basically, you need:

  • config HAProxy (/etc/haproxy/haproxy.cfg) to add new headers during forwarding: option httpclose // rewrite every request instead of first one option forwardfor
  • Read these header entries for the correct values: HTTP_X_FORWARDED_FOR // IP HTTP_X_FORWARDED_PORT // Port
As a precaution, one should check both HTTP_X_FORWARDED_FOR and REMOTE_ADDR so that the app can handle both situations.

Enjoy!