Redirecting example.com/* to www.example.com/*

.htaccess301-redirectredirect

I just moved to a new host and they've got a different control panel than the one I was using before. On my old host, all domain.com/* addresses were 301 redirected to www.example.com/*, without me having to configure anything and I'm trying to reproduce this on my current host.

After doing some searching, I found the following .htaccess code, which I put in my site's root .htaccess file:

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

And this works, redirecting all example.com/* pages to www.example.com/*, except for when I visit example.com/forum. If I access my forum by visiting www.example.com/forum, for some reason it's redirected to example.com/forum (no www). It didn't do this before.

So then what I did was put a modified version of the above code at the top of my forum's .htaccess file (which is located at /forum), the only difference being the addition of "/forum" on the last line:

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

This works, but I'm just wondering if I'm going about doing this "the right way" or there's another way that's superior?

Best Answer

The rules I use in the docroot's .htaccess

RewriteCond %{HTTP_HOST}   ^[^.]*?\.?([^.]+\.[^.]+)$
RewriteCond %{HTTP_HOST}   !^www\.                         [NC]
RewriteRule ^(.*)$         http://www.%1/$1                [L,R=301]
Related Topic