3

What’s the best way to automate creation of subdomains (like Basecamp)?

My requirement is somewhat similar to Basecamp where users request for a subdomain from a page and I create it for them from my business logic.

Something like alt text

Glorfindel
  • 1,213
  • 4
  • 15
  • 22
Quintin Par
  • 4,373
  • 11
  • 49
  • 72

2 Answers2

8

We use the same technique at our site. Our servers run Apache, MySQL and PHP on Linux.

Our DNS record contains a subdomain wildcard entry like EK already suggested:

www                      IN A       123.456.789.012
*                        IN CNAME   www

This will redirect all the requests to x.y.yourdomain.com to the same ip as www.yourdomain.com - it's also possible to have subdomains of subdomains.

I don't know perl, but in PHP you can access the host name at any time like this:

$_SERVER['HTTP_HOST']

I am sure there is an equivalent in Perl to access the Host-Header of the HTTP-Request. We use a central PHP script file for this purpose.

Edit: Found some time to provide further details on handling of these domains.

You may save the complete subdomain as a primary key in your database. This guarantees the user entered domains to be unique. You may also use this info for availability checks during registration of your user.

I guess your application can handle multiple users via an user id or sommething like this. Just save this user id together with the subdomain in the database. Now you can lookup the user id by the current domain sent via the HTTP-Host header at any time.

Zim
  • 98
  • 3
  • 2
    In Perl, this is accomplished using CGI and the %ENV hash -- from CGI, you could access it like so: "my $host = $ENV{HTTP_HOST};" – Sam Halicke Nov 21 '09 at 19:12
  • Wonderful answer! I was wondering if there were any issues with this approach. – Quintin Par Nov 21 '09 at 20:07
  • this won't have much of an impact on performance. we've been using this approach for >1.5 years now and didn't encounter any issues so far – Zim Nov 21 '09 at 20:52
  • And if you have predefined subdomains you just store it in a for example - file, and exclude them in a PHP condition? – benqus May 16 '12 at 13:16
5

set a wildcard on your domain for *.yourdomain.com. Then in code the used server name is in the header, simply read that to serve up customised content or redirect to a subfolder as required.

JamesRyan
  • 8,166
  • 2
  • 25
  • 36