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 share everything I know about web development and SEO.

My agency is also offering free site audits for a limited time. Take me up on it while you can!

Related Articles
More like this
How to Render Plain Text Templates in Ruby on Rails
Prevent an Infinite Loop When Using after_save in Rails
How to Fix "Address already in use – bind(2) for “” port 3000 (Errno::EADDRINUSE)"
Best Software Development Blogs -