I just recently started using CloudFlare and still have the lingering issue of getting CloudFlare's proxy IP addresses instead of my visitor's address. CloudFlare has many solutions for this, but I haven't seen any for Rails.
I'm using Rails 3.2.17.
It looks like if I initialize ActionDispatch::RemoteIp with the custom_proxies argument set to the proper regular expression that contains all of CloudFlare's IP ranges (along with all of the standard local and private ranges), it might solve my issue.
Questions:
1) Is this the right approach?
CloudFlare has a crap ton of IP ranges that all need to be converted to regular expressions. These ranges could change in the future, even though CloudFlare says they don't often, and I'd probably not know so it seems kind of brittle.
2) How do I initialize ActionDispatch::RemoteIP with the custom_proxies argument?
You can use the Rack middleware from the remote_ip_proxy_scrubber gem to make sure your Rails app ignores IP addresses from trusted proxy servers like CloudFlare.
First, add the gem to your Gemfile and then
bundle install
Now you'll need the updated list of CloudFlare IP addresses: https://www.cloudflare.com/ips-v4
Using that list of CloudFlare IPs, add the following to config/application.rb or conifg/environments/*.rb
Tracking changes to the list of CloudFlare IPs hasn't been too problematic for our company thus far.
Since Cloudflare abides to best-practices, and uses the
X-Forwarded-For
HTTP header, you just need to make sure to use it properly.Specifically for rails, this has already been asked several times, such as What's the difference between request.remote_ip and request.ip in Rails?
"These ranges could change in the future, even though CloudFlare says they don't often,"
The more likely thing is that we would add new ranges to our existing ranges (we also don't use new ips for quite some time so that people can adjust to the new ranges).
"Since Cloudflare abides to best-practices, and uses the X-Forwarded-For HTTP header, you just need to make sure to use it properly."
This is also correct:)