将example.com/*redirect到www.example.com/*

我刚搬到一个新的主机,他们有一个不同于我以前使用的控制面板。 在我的旧主机上,所有的domain.com/*地址被301redirectwww。 example.com/*,没有我必须configuration任何东西,我想重现我的当前主机。

在做了一些search之后,我发现了下面的.htaccess代码,我把它放在我的网站的根.htaccess文件中:

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

而这个工作, 除了当我访问example.com/forum时,将所有example.com/*页面redirect到www.example.com/*。 如果我通过访问www.example.com/forum访问我的论坛,由于某种原因,它被redirect到example.com/forum(没有www)。 它没有这样做过。

所以我做了上面的代码的修改版本在我的论坛的.htaccess文件(它位于/论坛)的顶部,唯一的区别是在最后一行添加“/论坛”:

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

这是有效的,但我只是想知道如果我正在做这个“正确的方式”,还是有另一种优越的方式呢?

我在docroot的.htaccess中使用的规则

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

你只需要一个root权限的.htaccess:

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

你的.htaccess文件中是否有其他的重写规则? 如果是这样的话,把你显示的前3行放在其他重写规则的上面。

当我这样做,example.com/xyzredirect到www.example.com/xyz。

我的.htaccess文件位于我的webroot(Ubuntu Lucid上的/ var / ww)。