Stéphane Balet
Stéphane Balet

Reputation: 71

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

Upvotes: 7

Views: 13697

Answers (3)

Yusuke
Yusuke

Reputation: 51

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.

Upvotes: 5

David B
David B

Reputation: 33

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

Upvotes: 3

Scott Stevens
Scott Stevens

Reputation: 2651

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]

Upvotes: 22

Related Questions