Skip to content

Instantly share code, notes, and snippets.

@johnrees
Created January 24, 2012 14:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnrees/1670449 to your computer and use it in GitHub Desktop.
Save johnrees/1670449 to your computer and use it in GitHub Desktop.
Remote IP on Heroku
def remote_ip
if forwarded = request.env["HTTP_X_FORWARDED_FOR"]
forwarded.split(",").first
elsif addr = request.env["REMOTE_ADDR"]
addr
end
end
@raimo
Copy link

raimo commented Jun 4, 2014

request.env["HTTP_X_FORWARDED_FOR"].try(:split, ',').try(:first) || request.env["REMOTE_ADDR"]

@bnorton
Copy link

bnorton commented Jun 11, 2015

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"]

@philtr
Copy link

philtr commented Oct 6, 2016

For Rails > 2.3.2, you should be able to use request.remote_ip (Docs)

@zackster
Copy link

@philtr @bnorton if you are using heroku + rails + cloudflare, then user_ip_addr = request.env["HTTP_X_FORWARDED_FOR"].try(:split, ',').try(:first) || request.env["REMOTE_ADDR"] is the correct solution

@jrochkind
Copy link

jrochkind commented Jul 19, 2022

@zackster why not request.remote_ip on heroku + rails + cloudflare?

@zackster
Copy link

@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