Reputation: 1
I have 5 unique unrelated domains. In the main domain (hosting package has root one with other domains in folders) I need to redirect all non-www urls to www. I used this code in my .htaccess file on the main domain:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mysite\.co.za
RewriteRule (.*) http://www.mysite.co.za/$1 [R=301,L]
It worked for the main domain, but now makes all my other domains (eg www.myothersite.com ) forward to an url like this:
//mysite.co.za/myotherdomain.com/home
How can I prevent this.
Upvotes: 0
Views: 1306
Reputation: 519
Short and incl. HTTPS
RewriteEngine on
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Upvotes: 1
Reputation: 1842
The right way to do this is:
# enable rewrite engine
RewriteEngine on
# if requested hostname does NOT start with "www."
RewriteCond %{HTTP_HOST} !^www\.
# get hostname to %1 variable
RewriteCond %{HTTP_HOST} ^([a-z]+\.[a-z]+)
# prepend "www." to requested hostname and file
RewriteRule (.*) http://www.%1/$1 [R=301,L]
If you want to be more specific and only include certain domains, use:
# enable rewrite engine
RewriteEngine on
# if requested hostname does NOT start with "www."
RewriteCond %{HTTP_HOST} !^www\.
# and if one of these hostnames, then get it to %1 variable
RewriteCond %{HTTP_HOST} ^(domain1\.com|domain2\.com|mysite\.co\.za)
# prepend "www." to requested hostname and file
RewriteRule (.*) http://www.%1/$1 [R=301,L]
So in the RewriteCond %{HTTP_HOST} ^(domain1\.com|domain2\.com|mysite\.co\.za)
line you would add all domains that need to be redirected.
Upvotes: 0