Log real client IP address

Hi, our rails backend is hidden from the Internet behind a 3-level HTTP proxies. The IP address logged by rails shows the outermost proxy’s (Fastly) public address, which is obviously not what we want. Some debugging showed that both X-Forwarded-For & Fastly-Client-IP HTTP headers have the real client’s IP address in them. Please advise on how to configure Rails properly.

Here’s an example log line:

2024-02-07 21:43:03 +0000 severity=INFO pid=28, method=GET path=/ format=html controller=Front::HomeController action=show status=200 duration=43.90 view=25.54 db=11.39 params={“checkip”=>nil} cookies={:locale=>“en”} ref_id=FOO ip= country_code=US is one of Fastly’s addresses, and it should be whatever’s in X-Forwarded-For, preferably.

I should note that in X-Forwarded-For received the first address is the real address, then comes Fastly’s address. Could the order matter? FWIW even setting X-Forwarded-For to the real client address right before forwarding the request to the actual backend doesn’t have any effect on the address shown in the log line - still Fastly’s address is logged.

Make sure you’re calling request.remote_ip in Rails. The linked docs explain how it works.

If you’re talking specifically about which IP address rails displays in its logs by default, that’s a different question. Hope you figure it out.

1 Like