Published on 2013-06-05 by John Collins. Please follow me on Twitter for more:
If you have a domain like alphaframework.org and you want to force your visitors to use www.alphaframework.org, you can achieve this using various Apache configuration directives. Most of the examples I have seen online use mod_rewrite, but you can save yourself the complexity and overhead by using two virtual host directives instead.
Here is an example configuration from my /etc/httpd/conf/httpd.conf file (this is typically where the main configuration file is located on Redhat-based systems):
<VirtualHost *:80> ServerName alphaframework.org Redirect permanent / http://www.alphaframework.org/ </VirtualHost> <VirtualHost *:80> <Directory /var/www/current> AllowOverride All </Directory> DocumentRoot /var/www/current ServerName www.alphaframework.org </VirtualHost>
The first virtual host entry captures all traffic to port 80 destined for the server named alphaframework.org, and then re-directs this traffic to www.alphaframework.org. The second virtual host entry is the real entry that points to the directory where the source code resides. A simple but effective trick.