Archive for July, 2009

Apache Wildcard Subdomains *.example.com

Every account for our server monitoring application, Server Density, is accessed under a unique URL such as http://example.serverdensity.com. This gives each account a unique identifier for our internal account management system.

Although each customer has their own database which is linked by their unique URL, there is only 1 copy of the application code itself. Wildcard domains are used to allow any subdomain to be used.

*.serverdensity.com

means you can use

hello.serverdensity.com
cheese.serverdensity.com
whateveryouwant.serverdensity.com

without needing any kind of additional configuration of Apache or the DNS for serverdensity.com.

In our DNS zone for serverdensity.com, we have the usual entries but there is also the following record:

*.serverdensity.com. serverdensity.com. CNAME

This refers to

serverdensity.com. 67.23.6.201 A

because we currently have a single server set up for beta test accounts. As the service grows, this will be replaced by appropriate load balanced servers but for now, a single machine is handling requests.

The Apache config uses name based virtual hosts and we define a single vhost for the *.serverdensity.com domain:

ServerAdmin customer.service@boxedice.com
ServerName *.serverdensity.com
DocumentRoot /path/to/sd/
ErrorLog /path/to/sd/error.log

All requests to any subdomain are therefore picked up he DNS wildcard and passed to Apache, which also handles the wildcard, with the application code handling the requests. The subdomain used is made available in PHP in the $_SERVER['SERVER_NAME'] variable so it is easy to pick out which customer database to load.

The advantages of this system are:

  • Only a single copy of the Server Density application code base needs to be deployed.
  • Customers can have their own unique URL.
  • No additional configuration is required for domains or Apache, which would result in large config files.
  • Requests are all handled by a single DNS zone which makes it easy to swap in a load balancer to distribute requests across multiple servers.
  • Requests can be individually linked to customer accounts so we could track down heavy usage or link error reports to a customer to help us reproduce and diagnose problems faster.