Force www in htaccess, with the exception of all subdomains

my force www htaccess code:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

but I have problems with ex subdomains :

abcdef.example.com  ====> www.abcdef.example.com

and I want to edit the code to work as follows:

example.com         ===> www.example.com
abcdefg.example.com ===> abcdefg.example.com
example.co.uk       ===> www.example.co.uk
abcd.example.co.uk  ===> abcd.example.co.uk
+4
source share
1 answer
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.(co\.uk|com)
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Or more general:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^[0-9a-zA-Z-]+\.[a-zA-Z]{2,}$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
+4
source

All Articles