Wildcard sub-domains and routes

Armand du Plessis wrote:


I've got a requirement which requires my site to accept all subdomains
e.g. sub1.domain.com, sub2.domain.com, sub3.domain.com etc and handle
them accordingly. I'm currently investigating the options for dealing
with this.

Would it be possible to this with routes or would I need to rewrite
the urls before it gets to rails? e.g. it would need to rewrite
sub1.domain.com -> domain.com/x/y/sub1

The server would be running Apache and I believe i would be able to
rewrite it there but 1st prize if I can do it with routes.

I'm very new to Rails, loving every minute btw, but a bit stuck on
this so any pointers would really be appreciated.

You could either route all subdomains to your Rails application and let the application decide what to do based on the subdomain or you could do some apache rewrite magic like you suggest. Assuming subdomains of the form you mentioned above the subdomain can be extracted in the controller simply with "request.subdomains[0]".

Actually, that’s not what Jacob means.

It’s quite simple actually: if you want to use one application with one database, but identify customer accounts with a subdomain, you have to pass the subdomain to Rails and let it either store the company in a session or use an application-wide before_filter to look up the subdomain. Using a subdomain shifts the emphasis from your website url to the customer, he gets the feeling it’s his private space (or at least that’s how i like to look at it) and it reads a lot better.

You could use Apache rewrite to rewrite the url mycustomer.mydomain.com to mydomain.com/mycustomer, but it doesn’t make a difference if you’re search for the customer in the database anyway.

There are two plugins I’ve used in the past for subdomain based routing: account_domain and request_routing, both work fine. Don’t forget to add ServerAlias *.mydomain.com in your virtual host definition as well as add the wildcard domain to your dns.

Apache rewrites can be very useful, e.g. if you want to run a separate mongrel for some or all customers. It has quite a few other uses too, but these are out of the scope of this thread.

Best regards

Peter De Berdt