Forcing non-WWW traffic to WWW on Apache without mod_rewrite

A tutorial on forcing non-WWW traffic to be redirected to WWW on Apache without the use of mod_rewrite.

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.

John Collins

I have been writing about web technology and software development since 2001. I am the developer of the Alpha Framework for PHP, and the five.today personal productivity app. I love open source, technology, and economics.