How to redirect multiple domains to “www.” with mod_alias “Redirect” directive

apache-2.2mod-aliasredirect

I'm trying to redirect multiple VirtualHosts without a preceeding "www." from one VirtualHost to another, like so:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias example.org
    ServerAlias example.net
    # I either need some kind of Apache conditional here...
    Redirect 301 / http://www.example.com/
    # ... or I need to substitute the Redirect *URL* with a variable
    # for the ServerName/ServerAlias
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
</VirtualHost>

I could just create several VirtualHost containers and redirect each one individually, but I prefer not to repeat my code, if possible.

I'm using Apache 2.2 and I prefer not to use mod_rewrite to redirect. I'm fair with Apache, but far from an expert.

Best Answer

I wrote the following condition that I'm using in an .htaccess file for redirecting any domain without the "www", this work for any domain name. The domain look could be done more comprehensive, for instance I only look for number, letters and underscore in the domain name since I know all the domains where this rule will apply will have just that, but you could easily replace the regular expression with a more complex one if you need.

  RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9-_]*)\.([a-zA-Z0-9]{2,3})$ [NC]
  RewriteRule ^(.*)$ http://www.%1.%2/$3 [L,R=301]