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:
- Top-level domain consolidation.
- 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.
1 2 3 4 5 6 7 8 9 10
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.
1 2 3 4 5
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.