Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect all non www to www except one subdomain with htaccess

I'd 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 redirect like this, or I get an error.

So I'd like to redirect any URL that does not begin with sub or with www to www.example.com

How can I do this ? thanks

like image 830
Stéphane Balet Avatar asked Aug 06 '12 15:08

Stéphane Balet


3 Answers

You need a second RewriteCond. You can apply as many as you like to a RewriteRule.

Assuming anything that is not sub.mydomain.com needs to 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 further using the pipe (|) character in Regex:

RewriteCond %{HTTP_HOST} !^(sub|www).mydomain.com$
RewriteRule ^(.*) http://www.mydomain.com/$1 [QSA,L,R=301]
like image 112
Scott Stevens Avatar answered Nov 16 '22 22:11

Scott Stevens


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. have fun.

like image 44
Yusuke Avatar answered Nov 16 '22 21:11

Yusuke


I tried the answer by Scott S but it didn't work, so I modified to use the one I was using 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

like image 3
David B Avatar answered Nov 16 '22 21:11

David B