Rails: block VPN and proxy users with a before_action
By Muntaha Shaheen · · 7 min read
To block VPN users in Rails, add a controller concern with a before_action that sends request.remote_ip to a detection API such as POST https://iplogs.com/v1/check. Configure config.action_dispatch.trusted_proxies first, because remote_ip is the visitor's address only once Rails knows which proxies are yours. Setting that option replaces the defaults, so add them back. Call the API from a small service on Net::HTTP with open, read and write timeouts, and cache each verdict with Rails.cache.fetch and skip_nil: true so a failed lookup is never stored. Treat a timeout, an error or a 429 as allow, so an unreachable API never stands between a real user and the form. Render 403 only for vpn_detected, because refusing everything above clean would shut out iCloud Private Relay users and people on work VPNs. Run the check before the password check on sessions, registrations and checkout. For softer handling, let the signup through and review flagged accounts in a background job.
The Rails check from proxy setup to the 403
Set trusted_proxies
remote_ip is the visitor's address only once Rails knows your proxies. Setting the option replaces the defaults, so add them back.
Run the check in a before_action
Before the password check on sessions, registrations and checkout.
Ask the API with timeouts
Net::HTTP open, read and write timeouts, and skip_nil so a failed lookup is never cached.
Render 403 only for vpn_detected
A timeout, an error or a 429 means allow.
By the time a Rails controller runs, most of the client-IP work is done. ActionDispatch::RemoteIp has looked at X-Forwarded-For, Client-Ip and the socket address and left its answer in request.remote_ip. The one thing it can't work out is which proxies belong to you, and until config.action_dispatch.trusted_proxies says so, a VPN check may be judging your CDN instead of the visitor.
The rest is a plain-Ruby service on Net::HTTP, so there's no gem to add, and a concern that controllers opt into. It runs on Rails 7.x and 8.x. If the API is slow or unreachable, or has rate-limited you, the request goes through unchecked.
How do I block VPN users in Rails?
Run a before_action on the actions where an anonymous network matters, typically create on sessions, registrations and checkout, and have it send request.remote_ip to the detection API. Check trusted_proxies before anything else, because remote_ip is only the visitor's address once Rails knows your proxies. The call itself lives in an IpCheck service with short Net::HTTP timeouts, a 15-minute Rails.cache.fetch that never stores a failure, and a pause whenever the API answers 429.
request.remote_ip vs request.ip: which should I use?
Use request.remote_ip, the address Rails itself uses, after configuring trusted proxies. The two methods come from different layers and treat X-Forwarded-For differently:
| request.ip | request.remote_ip | |
|---|---|---|
| Comes from | Rack (Rack::Request) | Rails (ActionDispatch::RemoteIp middleware) |
| Reads X-Forwarded-For | Only when REMOTE_ADDR is a private or loopback address | Yes, before falling back to REMOTE_ADDR |
| Trusted proxies | Rack's built-in list of private and loopback ranges | config.action_dispatch.trusted_proxies, defaulting to private, loopback and link-local ranges |
| Spoofing check | None | Raises IpSpoofAttackError when Client-Ip and X-Forwarded-For disagree (on by default) |
remote_ip takes the list of addresses, removes your trusted proxies, and returns the last one left: the address your outermost proxy saw. Its source carries a warning in capitals: if you don't use a proxy, it makes you vulnerable to IP spoofing. The middleware assumes a proxy is setting the headers. If Puma's port is reachable straight from the internet, any client can send X-Forwarded-For and choose its own remote_ip. Firewall the app server so only your proxy can reach it.
The same value drives rate_limit, the controller macro added in Rails 7.2, which keys on request.remote_ip unless you pass by:. With the wrong proxy list your throttle counts the CDN as one very busy user, or lets anyone who forges the header start a fresh count.
How do I configure trusted proxies in Rails?
If your proxy runs on a private network or on the same host, you may not need to: the defaults already cover 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8, fc00::/7 and the link-local ranges. Public proxies such as a CDN have to be added, and setting the option replaces the defaults rather than extending them, so the code below adds them back.
For Cloudflare, which appends the connecting address to X-Forwarded-For, save its published ranges to a file:
{ curl -s https://www.cloudflare.com/ips-v4; echo; curl -s https://www.cloudflare.com/ips-v6; echo; } > config/cloudflare_ips.txt# config/environments/production.rb
require "ipaddr"
Rails.application.configure do
cloudflare = Rails.root.join("config/cloudflare_ips.txt").readlines(chomp: true).reject(&:empty?)
config.action_dispatch.trusted_proxies =
ActionDispatch::RemoteIp::TRUSTED_PROXIES + cloudflare.map { |range| IPAddr.new(range) }
endThe value has to be an array (Rails raises ArgumentError for a single IPAddr). The two echo calls matter: at the time of writing Cloudflare's lists don't end with a newline, and without them the last IPv4 range and the first IPv6 range end up glued together on one line.
How do I set Net::HTTP timeouts for the API call?
Pass open_timeout, read_timeout and write_timeout to Net::HTTP.start. Left at its default, the open timeout is 60 seconds, and nobody waits a minute for a signup form.
# app/services/ip_check.rb
require "net/http"
class IpCheck
ENDPOINT = URI("https://iplogs.com/v1/check")
BACKOFF_KEY = "iplogs:backoff"
NETWORK_ERRORS = [Timeout::Error, SocketError, SystemCallError, IOError,
OpenSSL::SSL::SSLError, JSON::ParserError].freeze
# The iplogs verdict as a Hash, or nil when there is no answer. nil means allow.
def self.call(ip)
return nil if ip.blank? || Rails.cache.exist?(BACKOFF_KEY)
Rails.cache.fetch("iplogs:#{ip}", expires_in: 15.minutes, skip_nil: true) do
fetch_verdict(ip)
end
end
def self.fetch_verdict(ip)
response = Net::HTTP.start(ENDPOINT.host, ENDPOINT.port, use_ssl: true,
open_timeout: 2, read_timeout: 5, write_timeout: 5) do |http|
http.post(ENDPOINT.path, { ip: ip }.to_json, "Content-Type" => "application/json")
end
case response
when Net::HTTPOK
JSON.parse(response.body)
when Net::HTTPTooManyRequests
wait = response["Retry-After"].to_i
Rails.cache.write(BACKOFF_KEY, true, expires_in: wait.positive? ? wait : 60)
nil
else
Rails.logger.warn("iplogs returned #{response.code} for #{ip}")
nil
end
rescue *NETWORK_ERRORS => e
Rails.logger.warn("iplogs check failed for #{ip}: #{e.class}: #{e.message}")
nil
end
private_class_method :fetch_verdict
endWithout skip_nil: true, Rails.cache.fetch would store the nil from a failed lookup and hand it back for the next 15 minutes. With it, nothing is written and the following request tries again.
The rescue list is broad on purpose. Net::OpenTimeout, Net::ReadTimeout and Net::WriteTimeout all inherit from Timeout::Error, refused and reset connections arrive as SystemCallError, and a garbled body raises JSON::ParserError. Each one ends as nil. So does a 429, which the API returns once you go past 60 requests a minute; before returning, the service writes a backoff key that lasts as long as Retry-After says, and nothing calls out until it expires. The concern reads nil as "allow", so an unreachable API never stands between a real user and the signup form.
How do I run the check in a before_action?
Put the decision in a concern so any controller can opt in, and choose the actions in each controller:
# app/controllers/concerns/blocks_anonymous_ips.rb
module BlocksAnonymousIps
extend ActiveSupport::Concern
private
def block_anonymous_ip
@ip_verdict = IpCheck.call(request.remote_ip)
return unless @ip_verdict&.dig("verdict") == "vpn_detected"
render plain: "Please turn off your VPN or proxy and try again.", status: :forbidden
end
end# app/controllers/sessions_controller.rb (same for registrations, checkout)
class SessionsController < ApplicationController
include BlocksAnonymousIps
before_action :block_anonymous_ip, only: :create
# ...
endWhen a before_action renders, Rails doesn't run the action and cancels any later callbacks, so a blocked request never reaches create. Requests that pass carry @ip_verdict, which the action can use for softer handling: if is_vpn or is_proxy is true but the verdict is below vpn_detected, require email confirmation or hold the order for review.
vpn_detected starts at a score of 0.85. Below it sit vpn_likely (from 0.60), suspicious (from 0.30) and clean. Refusing everything above clean would shut out iCloud Private Relay users and people on work VPNs, most of whom are genuine. Nor does clean rule out a residential proxy: judged on the IP alone, those exits are close to invisible.
Should the check run before or after the password check?
Before, which is what a before_action on SessionsController#create gives you. The VPN check runs before the action authenticates anyone, so a blocked visitor gets the same 403 with a correct password as with a wrong one. If you blocked only after a successful login, someone working through a list of stolen passwords over a VPN could tell the valid ones from the invalid ones by which response came back.
The cache keeps this cheap during an attack: once an address has been checked, every attempt from it for the next 15 minutes is answered from Rails.cache, not from the API.
How do I test the VPN check in Rails?
bin/rails runner gives a live answer without touching a controller. Here it is against 192.42.116.44, a Tor exit relay on the published list as of 27 October 2026:
$ bin/rails runner 'v = IpCheck.call("192.42.116.44"); puts v["verdict"], v["ip_info"]["vpn_provider"]'
vpn_detected
TorThen confirm the proxy setup on the real deployment. Log request.remote_ip next to request.remote_addr for a request you make yourself, and check both against what the iplogs.com self-check reports for your connection. If remote_ip shows a Cloudflare or load balancer address, that range is missing from trusted_proxies.
What are the free API limits for a Rails app?
Every lookup leaves from your server, so the app gets one shared allowance: 60 requests a minute, and 2,000 full checks a day, counted from midnight UTC. There's no key to manage. Going over the daily figure doesn't produce errors: the API answers HTTP 200 in fast mode and skips the live probes. You can pick that mode yourself on a latency-sensitive path like login by adding mode: "fast" to the JSON body, which comes back in microseconds. Key the cache on the mode as well, or a fast verdict will be reused where you wanted a full one.
Can I check users after signup instead of blocking them?
Yes, and for many products it's the better default. Let the signup through, then run the check in a background job and flag the account for review. The user never waits on the API, and a false positive costs a review instead of a lost customer. With Active Job (Solid Queue is the default backend in current Rails), assuming a boolean needs_review column on users:
# app/jobs/ip_screening_job.rb
class IpScreeningJob < ApplicationJob
queue_as :default
def perform(user, ip)
verdict = IpCheck.call(ip)
return unless verdict && (verdict["is_vpn"] || verdict["is_proxy"])
user.update!(needs_review: true)
end
end
# app/controllers/registrations_controller.rb, after @user.save succeeds
IpScreeningJob.perform_later(@user, request.remote_ip)The job uses the same service and the same cache, so a user who signs up and then logs in from the same address costs one lookup, not two. For accounts created before the check existed, a job can work through POST /v1/bulk-check 100 IPs at a time; the endpoint allows a burst of three calls, after which it's one call every 5 seconds.
Questions people also ask
Does Rails have built-in VPN detection?
No. Rails resolves the client address with request.remote_ip and, since 7.2, can rate-limit by it, but it ships no data on which networks belong to VPN providers, proxies or Tor. That comes from an external API or dataset.
What's the difference between request.ip and request.remote_ip?
request.ip comes from Rack and reads X-Forwarded-For only when the connection comes from a private or loopback address. request.remote_ip comes from Rails' RemoteIp middleware, honours config.action_dispatch.trusted_proxies, and adds an IP spoofing check. Rails' own features, such as rate_limit, use remote_ip.
Why does request.remote_ip return a Cloudflare address?
Cloudflare's ranges aren't in Rails' default trusted proxies, so the Cloudflare edge is treated as the client. Add Cloudflare's published ranges to config.action_dispatch.trusted_proxies, keeping the defaults, as shown above.
Can X-Forwarded-For be spoofed in Rails?
Yes, if clients can reach your app server without going through your proxy. RemoteIp assumes a proxy sets the header. Make sure only your proxy can connect to Puma, and keep the default spoofing check enabled.
Should I use Rack::Attack instead?
They do different jobs. Rack::Attack is good at throttling and blocking addresses you already know about. A VPN check answers what kind of network an unknown address belongs to, so nothing stops you running both.
Sources
- Rails source: ActionDispatch::RemoteIp middleware
- Rails source: ActionController::RateLimiting
- Rails Guides: Configuring Rails Applications (ActionDispatch::RemoteIp)
- Rails Guides: Action Controller Overview (before_action, request object)
- Rails Guides: Caching with Rails (Rails.cache.fetch)
- Rails Guides: Active Job Basics
- Rails API: ActiveSupport::Cache::Store#fetch (skip_nil)
- Action Pack 7.2 changelog: Add rate limiting API
- Rack::Attack README
- Rack source: Rack::Request#ip and default trusted proxies
- Ruby source and docs: Net::HTTP (start options, timeouts)
- Cloudflare docs: Cloudflare HTTP headers
- Cloudflare IP ranges