Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

So, on my main domain 'domain.com' I created several subdomains from cPanel, like 'sub1.domain.com' and 'sub2.domain.com'. Their real location on server is in 'domain.com/sub1' and 'domain.com/sub2'.

Now, I want to redirect non www to www with .htaccess and this is what currently what i have:

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

This works. When somebody enter domain.com it will be redirected to www.domain.com. However when somebody enter sub1.domain.com, he will be redirected to www.domain.com/sub1 - which I don't want, it needs to be in sub1.domain.com.

What shall I add in .htaccess file to accomplish this?

share|improve this question

marked as duplicate by Jenny D, Ward, Jim B, mdpc, HBruijn Apr 5 at 6:23

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 5 down vote accepted

You can exclude each sub1, sub2 individually like so;

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_HOST} ^sub1\.domain\.com [NC]
RewriteRule ^(.*) - [L]

RewriteCond %{HTTP_HOST} ^sub2\.domain\.com [NC]
RewriteRule ^(.*) - [L]

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

Or just be specific that you only want to redirect domain.com to www.domain.com with the RewriteCond

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule ^(.*) http://www.domain.com/$1 [L,R=301]
</IfModule>
share|improve this answer
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.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.