Created
July 18, 2023 14:24
-
-
Save dpaluy/c138e9bbf2c47cd9ced7b3c707e3ea53 to your computer and use it in GitHub Desktop.
Rails middleware ensures the Rails stack obtains the correct IP
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
# config/initializers/cloudflare_real_ip.rb | |
# frozen_string_literal: true | |
# 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 | |
class CloudflareRealIp | |
def initialize(app, opts={}, &block) | |
@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 | |
Rails.application.config.middleware.insert_before 0, CloudflareRealIp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment