301 redirecting non-www to www does not always work

I read a ton of posts and pages trying to figure this out. I mainly work. I have a .htaccess file setup and I'm trying to redirect (301) any page on my site from non-www to www.

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

It seems to work from the base url. However, it does not redirect to sub pages.

It works:

example.com → www.example.com

This does not work:

example.com/foo.html → www.example.com/foo.html

Any help would be greatly appreciated

+3
source share
3 answers

I think you need to add \to avoid a dot in your domain (line 2).

How in:

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

... : http://www.hostingdiscussion.com/promotion-marketing/26083-301-redirect-non-www-www-vice-versa-good-search-engine-optimization-technique.html

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

Here is my rule that works in my prod environment:

# If domain name without "www", add them:
RewriteCond %{HTTP_HOST} ^mydomainname\.(fr|com|net|org|eu) [NC]
# without www => force redirection:
RewriteRule (.*) http://www.mydomainname.%1$1 [QSA,R=301,L]
0
source

All Articles