Skip to content

Instantly share code, notes, and snippets.

@mattheworiordan
Created March 28, 2014 09:05
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mattheworiordan/9828493 to your computer and use it in GitHub Desktop.
Save mattheworiordan/9828493 to your computer and use it in GitHub Desktop.
CloudFlare IP Middleware for Rails to ensure HTTP_CF_CONNECTING_IP is used and the clients IP is correct within Rails
module RailsAppName
class Application < Rails::Application
# .... your settings
require "#{Rails.root}/lib/cloud_flare_middleware"
config.middleware.insert_before(0, Rack::CloudFlareMiddleware)
# ... your settings
end
end
# CloudFlare masks the true IP
# This middleware ensures the Rails stack obtains the correct IP when using request.remote_ip
# See https://support.cloudflare.com/hc/en-us/articles/200170786
module Rack
class CloudFlareMiddleware
def initialize(app)
@app = app
end
def call(env)
if env['HTTP_CF_CONNECTING_IP']
env['HTTP_REMOTE_ADDR_BEFORE_CF'] = env['REMOTE_ADDR']
env['HTTP_X_FORWARDED_FOR_BEFORE_CF'] = env['HTTP_X_FORWARDED_FOR']
env['REMOTE_ADDR'] = env['HTTP_CF_CONNECTING_IP']
env['HTTP_X_FORWARDED_FOR'] = env['HTTP_CF_CONNECTING_IP']
end
@app.call(env)
end
end
end
@henrik
Copy link

henrik commented Nov 10, 2016

Thank you! ❤️

@maxkaplan
Copy link

Thanks for this!
Btw - there is a typo require "#{Rails.root}/lib/cloud_flare_middleware" should be require "#{Rails.root}/lib/cloudflare-middleware"

@saikumar-everest
Copy link

I see that we are setting environment variables. If I'm trying to make my code thread-safe to use Puma effectively with multi-threading, I guess this code isn't thread-safe right, because we are mutating the global shared space(for threads). What's the solution in this case? How should I proceed to make it thread-safe?

@webzorg
Copy link

webzorg commented Dec 15, 2022

Good one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment