Redirect all non www to www except one subdomain with htaccess

I would like to redirect all urls not containing www to www

I used this:

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

Now I need one subdomain not to be redirected, or I get an error message.

Therefore, I would like to redirect any URL that does not start with sub or from www to www.example.com

How can i do this? thanks

+7
source share
3 answers

You will need a second RewriteCond . You can apply as many as you want to the RewriteRule .

Assuming something that is not sub.mydomain.com should be www.mydomain.com , here is your code:

 RewriteCond %{HTTP_HOST} !^sub.mydomain.com$ RewriteCond %{HTTP_HOST} !^www.mydomain.com$ RewriteRule ^(.*) http://www.mydomain.com/$1 [QSA,L,R=301] 

But you can simplify this by using the pipe ( | ) symbol in Regex:

 RewriteCond %{HTTP_HOST} !^(sub|www).mydomain.com$ RewriteRule ^(.*) http://www.mydomain.com/$1 [QSA,L,R=301] 
+19
source

I tried answering Scott S., but that didn't work, so I changed it to use the one I used for general 301:

 RewriteCond %{HTTP_HOST} ^domain.com RewriteCond %{HTTP_HOST} !^subdomain.domain.com RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L] 

And it works like a charm

+3
source
 RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC] RewriteCond %{HTTPS}s ^on(s)| RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

This works for all domains, excluding any subdomains. enjoy.

+2
source

All Articles