Rails IP-Based access restriction with route constraints

Sometimes we need to limit access based on IP address and whitelist only certain IP addresses to access a route. We can use rails routing constraints to restrict an access. We can either whitelist or blacklist IP addresses for a route.

Rails provides different basic constraints on routes like:

Let’s say, we have a list of IP addresses to whitelist. We can configure such IP address in Rails configuration as given below.

# In config/environments/development.rb

config.whitelisted_ips = ['', '']

Now, we can use whitelisted_ips to define a constraint to restrict access to any other IP addresses than in the list.

  • Define a constraint
# In lib/constraint/ip_authenticator.rb
module Constraint
  class IPAuthenticator
    def matches?(request)

  • Apply the constraint to a route
# In config/routes.rb
Rails.application.routes.draw do
    # constraints on a resource
    constraints Constraint::IPAuthenticator.new do
        resources :users

    # constraints on a route
    get "list_user", to: "user#index",
        constraints Constraint::IPAuthenticator.new

If the remote_ip address of the request object matches the constraints we then only the request is served otherwise rails responds the request with ActionController::RoutingError (No route matches)


Apart from the basic routing constraints, one can add some advanced constraints on route/routes. Restricting the access to a route based on the IP address is also possible


Leave a Comment
