Steve
Steve

Reputation: 1765

.htaccess: how to redirect non-www to www except for subdomains

I've used the following code to redirect example.com to www.example.com:

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

However, I have www.example.com set up in Wordpress multisite with subdomains, so I need the above rule to only work for example.com, and not for site-x.example.com.

Upvotes: 1

Views: 46

Answers (2)

josephting
josephting

Reputation: 2665

This will apply to example.com and only example.com.

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
  1. Check if HTTP_HOST starts with example.com and ends here. Stop if false, continue if true.
  2. Redirect to URL with leading www.

Upvotes: 0

Ultimater
Ultimater

Reputation: 4738

Some options:

The rather generic:

RewriteCond %{HTTP_HOST} ^\w+\.\w+$

A blacklist:

RewriteCond %{HTTP_HOST} !^(www|site-x)\. [NC]

Or a whitelist:

RewriteCond %{HTTP_HOST} ^(example1|example2)\.(com|net|co)$ [NC]

Upvotes: 2

Related Questions