Routing Multiple Domains in a Ruby on Rails App

A Ruby on Rails app can accept multiple domains or subdomains, and route visitors to different places depending on the domain. This allows me to run multiple projects on the same Rails app, which saves me money and makes it easier to build features that can be shared by multiple projects.

You can wrap a set of resources or endpoints in constraints where they are only active if the constraints are satisfied, or in this case, if the request is made on a particular domain or subdomain.

Here's an example of how we can route visitors on our shop subdomain:

In our routes.rb

require 'shop_domain'

constraints(ShopDomain) do
  resources :shop
  get '/subscription', to: 'shop#subscription'
  root to: 'shop#index'

Then we define our ShopDomain class to filter certain domains or subdomains. I usually place these files in the lib directory.

class ShopDomain
  def self.matches? request
    request.subdomain == 'shop'

You can easily swap out request.subdomain for other criteria. I use this trick to map unique domains to their own controllers and views which lets me run a single Rails app that powers multiple websites.

All traffic still hits the same Rails app and all data lives in the same database which makes my life easier.

This approach lets me share code and build a feature for multiple projects simultaneously rather than having to rebuild a feature that I may want in every separate app I develop.

Plus this approach is way more cost-effective than spinning up separate servers for each website.

Level up faster
Recommended Books
Check out my list.
One on Ones: 101
Leveraging Other People's Experience
Hey, I'm Nicholas Dill.

I help people become better software developers with daily tips, tricks, and advice.

Level up
Related Articles
More like this
Understanding the #any? Method in Ruby
The Differences Between #nil?, #empty?, #blank?, and #present?
How to Generate a Simple Sitemap with Ruby on Rails