.htaccess – subdomain not working with www

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

I have a domain www.example.com and I have set .htaccess file to redirect all example.com to www.example.com

Now, I made (through my plesk 10 interface) a subdomain abc.example.com and what I would like is to also have www.abc.example.com so I entered (also in plesk) this:

www.abc.example.com.    CNAME   abc.example.com.

But it’s not working. Do I need to reload/restart dns?(if so, please tell me how?) Or do I just need to wait certain time for this until it propagates?

Since my mentioned CNAME didn’t work, I also added the .htaccess (which might be wrong (I know, not much of a server person 🙁 )) in the abc folder which looks like this:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^abc.example.com$
RewriteRule ^(.*)$ http://abc.example.com/$1 [R=301]

but with no luck, so please shed some light.

I found the solution myself in the end:

In Plesk I made one subdomain.domain.com pointing to lets say abc folder, and then I added the www.subdomain.domain.com also through Plesk but pointed it to the same abc folder. Then I added the .htaccess file inside this abc folder (where all other files for this subdomain reside) which now guarantees that all requests to subdomain.domain.com get redirected to www.subdomain.domain.com. Here is my .htaccess file:

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

Hope this will help someone beginning with this stuff like me.

Just to note, the credit for the idea of pointingthe www.subdomain inside the same folder goes to user Bryan White on serverfault

Written by Nikola Brežnjak