Many Sites in a single Heroku application

December 12, 2012 Link to post  Permalink

I recently wrote about using the same codebase to run multiple Heroku apps. There are some situations where it may be better to run multiple applications in a single Heroku app. The whole CRAZ8 domain is running as a single Heroku application, frankly because there’s not much at the root portion, and the Blog code isn’t very taxing with the number of users I have.

Rails 3.1 added some routing goodness to make this fairly easy to do. The typical use of sub-domains in a Rails application is to provide different users or accounts with a different url. For a low-traffic site like this, we can use this feature to host completely different systems under sub-domains, but all under a single codebase.

I have a root domain, craz8.com, a blog subdomain, and, if anyone uses ‘www.craz8.com’, I want to redirect them back to the root domain.

Here is a summary of my routes.rb file:

MyApplication::Application.routes.draw do
  constraints :subdomain => '' do
    root :to => 'site#root'

    # Other main site routes
  end

  constraints :subdomain => 'blog' do
    root :to => 'blog#show'

    # Other blog routes
  end

  constraints :subdomain => 'www' do
    match "/" => redirect("http://craz8.com/")
    match "/*other" => redirect { |params, req| "http://craz8.com#{params[:other]}" }
  end
end

You then need to tell Heroku about the sub-domains so that they send requests to your configured application:

heroku domains:add blog.craz8.com
heroku domains:add www.craz8.com
heroku domains:add crazy.com

Then configure your DNS provider to send all sub-domains to Heroku and deploy your app in the usual way.