CodeGnome Consulting, LTD

Programming - DevOps - Project Management - Information Security

Canonical Hostnames

| Comments

You can consolidate your domains, sub-domains, and hostnames with Apache 2 to provide a canonical destination for web requests. This can improve the user experience and simplify analytics.

Consolidating with Apache 2

It’s not unusual for a website to have more than one domain name pointing to its pages. Virtual hosting has a number of use cases, two of which we’ll consider today:

  1. Top-level domain consolidation.
  2. Sub-domain consolidation.

For these use cases, we’ll further assume that all domains point to the same set of server pages, and that the main reason for consolidation is for analytics. Whether or not these assumptions matter, it’s always useful to spell out your inherent assumptions when you try to solve a problem.

Defining the Virtual Hosts

The Apache web server has some useful tricks of the trade for this type of consolidation. The one we’ll use is the Redirect Directive. It’s often best to start by defining your canonical hostname using a default name-based virtual host.

/etc/apache2/sites-available/default
1
2
3
4
5
6
7
8
9
10
<VirtualHost *>
    ServerAdmin webmaster@example.com
    ServerName www.example.com

    DocumentRoot /var/www/example.com/

    LogLevel warn
    ErrorLog /var/log/apache2/error.log
    CustomLog /var/log/apache2/access.log vhost_combined
</VirtualHost>

The default vhost is used whenever another vhost isn’t explicitly matched. Its definition is relatively straightforward, so we won’t belabor it. The fun actually starts with the next vhost definition.

/etc/apache2/sites-available/consolidated_domain_names
1
2
3
4
5
<VirtualHost *>
    ServerName example.com
    ServerAlias example.org www.example.org www2.example.org
    Redirect / http://www.example.com/
</VirtualHost>

This time, we tell Apache to redirect the naked domain, as well as the set of alternative top-level domain names and sub-domains defined by ServerAlias, to the canonical hostname we defined in the default vhost.

Enabling the New Virtual Hosts

To spin all this up, just enable the sites and reload Apache. For example:

sudo a2ensite default consolidated_domain_names
sudo /etc/init.d/apache2 reload

That’s really all there is to it! All incoming requests that don’t match some other defined vhost will now be redirected to your canonical hostname at www.example.com.

Comments