Forum Moderators: phranque
<VirtualHost *>
ServerAlias example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost my-ip-address:80>
ServerName www-redirect
KeepAlive Off
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^\./]+\.[^\./]+$
RewriteRule ^/(.*)$ ht tp://www.%{HTTP_HOST}/$1 [R=301,L]
</VirtualHost>
The KeepAlive Off closes the connection directly after the 301 redirect is sent. This makes the apache instance available for new requests. Normally Apache will keep the line open for 15 to 25 seconds, depending on the overall KeepAlive settings in your httpd.conf.
The rewrite part looks voor all requests, where the HTTP_HOST variable contains two parts, separated with a dot. If this condition is met, the rewrite rule places www. at the beginning, and glues the rest of the URL behind the domain name.
This solution works fast because there is no overhead in the VirtualHost section, no cookies sent which may be the case for the main VirtualHost etc, closes the connection to free resources and works for all domains that are pointing to my server at once. No need to program individual rewrite sections for every single site I add to my server.