301 redirect non-www to www not always working
I've read through a ton of posts and pages trying to figure this out. I have it mostly working. I have a .htaccess file setup and I'm trying to redirect (301) any page in my site from non-www to www version.
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 doesn't redirect for sub pages.
This works:
example.com -> www.example.com
This does NOT work:
example.com/foo.html开发者_如何学C -> www.example.com/foo.html
Any help would be much appreciated
I think you need to add a \
to escape the dot in your domain (line 2).
As in:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^(.*)\.yourdomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]
...as seen here: http://www.hostingdiscussion.com/promotion-marketing/26083-301-redirect-non-www-www-vice-versa-good-search-engine-optimization-technique.html
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Here's my rule that work 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]
精彩评论