IdidntKnewIt
IdidntKnewIt

Reputation: 582

Change to www if not a subdomain

Plot: I actually like www URL's but not when used with subdomain like www.whatever.example.com . First i was using two domains on my hosting account so I added a htaccess rewrite like below code.

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

Motive: Now after sometime I realised that I need a subdomain also pointed to my hosting account. But I don't want a ugly subdomain like www.whatever.example.com but at the sametime I want to redirect example.com users to www.example.com. I am unable to figure out how to do that. Anyone here.

Upvotes: 2

Views: 94

Answers (2)

anubhava
anubhava

Reputation: 785511

You can use this rule to only target your main domain:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

Or else, to target any sub-URL down to 3 levels 'deep':

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^[^.]+\.[^.]+\.[^.]+$
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

Upvotes: 3

Zeeshan
Zeeshan

Reputation: 1675

Try this using .htaccess, Ref

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

Upvotes: 1

Related Questions