-
-
Save sergeylanzman/7a200484461bbd14ede394fd4d844264 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
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
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 |
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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment