Blog · Business · January 21, 2009
Hosting multiple domains from a single Rails app
Some of our reasons for doing this:
- Simplify the backend: server maintenance, releases, and hosting costs
- Repurpose existing CSS, images, javascript, etc
- Repurpose existing code (avoid complications of git submodules keeping shared code in sync between separate Rails apps)
However, we quickly realized that Rail’s doesn’t really support hosting a separate domain from the same app… at least, not out of the box. What we needed was the ability to use routing rules to specify that requests coming from our new domain, truecostofcredit.com, be directed to specific a Controller.
Fortunately, we came across a couple of extremely useful blog posts that helped solve this problem for us.
First, Jamis Buck gives this excellent clinic on the guts of Rails routing: Under the hood: route recognition in Rails
The most helpful resource for us was this: Rails routing based on hostname
We were able to adapt the code used in the above link for our purposes… allowing us to create custom routes that were conditioned on the domain name. Here’s what ended up in one of our initializers:
#
# This allows us to set up custom routes that depend on the domain or host of the request, ie:
# map.connect '', :controller => 'blah', :action => 'blah', :conditions => {:domain => 'blah'}
#
module ActionController
module Routing
class RouteSet
def extract_request_environment(request)
env = { :method => request.method }
env[:domain] = request.domain if request.domain
env[:host] = request.host if request.host
env
end
end
class Route
alias_method :old_recognition_conditions, :recognition_conditions
def recognition_conditions
result = old_recognition_conditions
result << "conditions[:domain] === env[:domain]" if conditions[:domain]
result << "conditions[:host] === env[:host]" if conditions[:host]
result
end
end
end
end
Then, we could use this in our routes.rb in the following way:
map.connect '', :controller => 'true_cost_calculator', :action => 'new', :conditions=>{ :domain=>'truecostofcredit.com' }
Thus… when someone visits truecostofcredit.com, they are directed to our TrueCostCalculatorController!
We loved this solution. It saved us a ton of time and effort, and kept our codebase nice and clean.
Fighting a chargeback, or paying too much?
The chargeback tool works with any processor. The statement audit is free.