I had to implement dynamic subdomains for a large Ruby On Rails application we had been developing. While the
most straightforward way of doing this is to code the functionality within your application, I decided on trying a different approach by doing everything server side.
For example, each time I access
http://daniel.myapp.com, this would send a request to the rails instance that may look like
http://myapp.com/profiles/daniel. On the other hand other static resources such as stylesheets and images, must still point to their original locations.
On Nginx my code resembled this:
location / {
set $subdomain "";
set $subdomain_root "";
set $doit "";
if ($host ~* "^(.+)\.myapp\.com$") {
set $subdomain $1;
set $subdomain_root "/profiles/$subdomain";
set $doit TR;
}
if (!-f $request_filename) {
set $doit "${doit}UE";
}
if ($doit = TRUE) {
rewrite ^(.*)$ $subdomain_root$1;
break;
}
# root ..
# proxy_set_header ..
# etc..
}
The $doit thing is just a hack meant to allow multiple if conditions on Nginx.