301 redirect non-www to www not always working

跟風遠走 提交于 2019-12-20 01:40:50

问题


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 -> www.example.com/foo.html

Any help would be much appreciated


回答1:


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




回答2:


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



回答3:


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]


来源:https://stackoverflow.com/questions/5972000/301-redirect-non-www-to-www-not-always-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!