Created
January 24, 2012 14:32
-
-
Save johnrees/1670449 to your computer and use it in GitHub Desktop.
Remote IP on Heroku
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def remote_ip | |
if forwarded = request.env["HTTP_X_FORWARDED_FOR"] | |
forwarded.split(",").first | |
elsif addr = request.env["REMOTE_ADDR"] | |
addr | |
end | |
end |
Shouldn't it be .last
??
curl -H 'X-Forwarded-For: x.y.z' http://httpbin.org/ip
#=> { "origin": "x.y.z, 73.25.72.189" }
request.env["HTTP_X_FORWARDED_FOR"].try(:split, ',').try(:last) || request.env["REMOTE_ADDR"]
For Rails > 2.3.2, you should be able to use request.remote_ip
(Docs)
@zackster why not request.remote_ip
on heroku + rails + cloudflare?
@jrochkind my post was 5 years ago.. yours is probably the correct answer for 2022. :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
request.env["HTTP_X_FORWARDED_FOR"].try(:split, ',').try(:first) || request.env["REMOTE_ADDR"]