If the domains always have two components (x.tld) then it's pretty easy. If you have to take into account things like x.co.uk then you'll need either a bigger rule or an actual list of the domains.
Not tested, but something like this might work.
# enable mod_rewrite
RewriteEngine On
# if the host is prefixed with www, don't match.
RewriteCond %{HTTP_HOST} !^www\.
# match the last two components of the hostname (see below for a bette regex)
RewriteCond %{HTTP_HOST} (.+?)\.(.+?)$
# rewrite to the hostname from the match above (%1 and %2) plus the current url ($1).
RewriteRule /(.*) http://www.%1.%2/$1 [L,R=301]
Add
LogLevel alert rewrite:trace
and you can grep for 'rewrite:' in your error log for debugging information.
The (.+?)
conditions might be more accurate as "anything but a dot" ([^\.]+)
, but I don't remember the exact syntax in whatever regex engine Apache uses, so the above version is simpler for you to have something working.
.com
? And presumably, any number of subdomains eg.www.sub1.domain1.com
? Anddomain1.com
should also redirect towww.domain1.com
?