Skip to content

Instantly share code, notes, and snippets.

@tompave
Created May 19, 2014 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tompave/942dec39d2112cced0d8 to your computer and use it in GitHub Desktop.
Save tompave/942dec39d2112cced0d8 to your computer and use it in GitHub Desktop.
client IP in Rails 3.2
# in a controller
# request.remote_ip -> http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-remote_ip
# default IP lookup -> http://api.rubyonrails.org/classes/ActionDispatch/RemoteIp/GetIp.html#method-i-calculate_ip
#
# request.remote_ip looks at different sources and makes a "best guess" to find the correct IP. This is usually easy
# with a plain app-server setup, but with reverse-proxy configurations (Mongrels behind Apache, Unicorns behind nginx) the
# requests are issued by the reverse-proxy (often localhost).
#
# Since we have a cluster of Unicorns behind a nginx reverse-proxy, the actual client IP is (almost) surely found in the
# HTTP_X_FORWARDED_FOR http header. If nil, we fallback to the default method.
#
# BTW, request.remote_ip checks HTTP_X_FORWARDED_FOR as well, but since we already know that the actual IP will (should) be
# there, let's try that directly first.
#
def get_client_ip_address
return request.env["HTTP_X_FORWARDED_FOR"] || request.remote_ip
rescue StandardError
return nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment