Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a full domain to a subdomain-based Rails app account?

Tags:

I'm developing a Rails app that by default sets up user accounts to a subdomain of their choosing. As an option, they will be able to map their own full domain to their account.

So far this is how I have things set up. I am using subdomain-fu to power the routing:

# routes.rb
map.with_options :conditions => {:subdomain => true} do |app|
  app.resources # User's application routes are all mapped here
end

map.with_options :conditions => {:subdomain => false} do |www|
  www.resources # Public-facing sales website routes are mapped here
end

In addition to that, I am using the method described here to get the account being accessed, via subdomain or full domain:

before_filter :set_current_account

def set_current_account
  if request.host.ends_with? current_domain
    # via subdomain
    @current_club = Club.find_by_subdomain(current_subdomain)
  else
    # via full domain
    @current_club = Club.find_by_mapped_domain(request.host)
  end
end

I haven't got very far down the process of building this yet, but already I can see I am going to run into problems with routing. If request.host is some random.com domain then subdomain-fu is not going to route the appropriate routes?

I'm assuming this isn't that unusual a problem, so can anyone share how they have tackled this problem, or how I would configure my routes to do what I need it to?

like image 963
aaronrussell Avatar asked Jan 15 '10 15:01

aaronrussell


1 Answers

You can write a Rack middleware that converts the domain into the subdomain before it hits the Rails application.

class AccountDetector
  def initialize(app)
    @app = app
  end

  def call(env)
    account = Club.find_by_mapped_domain(env["HTTP_HOST"])
    if account
      env["HTTP_HOST"] = "#{account.subdomain}.yourdomain.com"
    end

    @app.call(env)
  end
end

Then add that into environment.rb:

config.middleware.use AccountDetector
like image 142
Peter Avatar answered Oct 12 '22 09:10

Peter