JayKey JayKey - 2 months ago 6
Ruby Question

Rails - difference between request.env['HTTP_X_FORWARDED_FOR'] and request.remote_ip

I am adding some changes to existing RoR application and found out that

request.env['HTTP_X_FORWARDED_FOR']
returned
nil
. I changed that to
request.remote_ip
and got right IP address of the client.

Why does
request.remote_ip
return an IP when
request.env['HTTP_X_FORWARDED_FOR']
returns
nil
? What's the difference between them? How can I make
request.env['HTTP_X_FORWARDED_FOR']
work and which one should I use (best practice)?

Answer

Generally, you should use request.remote_ip. It is a method introduced by Rails which tries to gather the actual remote IP of the connection using various means, including evaluating request.env['HTTP_X_FORWARDED_FOR'] where appropriate.

In the end, the IP returned by request.remote_ip is calculated in the ActionDispatch::RemoteIp middleware. This is a good bit more generic than trying to gather the IP yourself as it takes proxy stages into account which can set various HTTP headers.

Comments