我有一个网站,似乎不能从非www重定向到www。
我的Apache配置如下:
RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^www.example.com [nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc]
我错过了什么?
我有一个网站,似乎不能从非www重定向到www。
我的Apache配置如下:
RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^www.example.com [nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc]
我错过了什么?
当前回答
<VirtualHost *:80>
ServerAlias example.com
RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>
这将重定向不仅域名,而且内部 pages.like…… example.com/abcd.html ==> www.example.com/abcd.html example.com/ab/cd.html ? ef = gh ==> www.example.com/ab/cd.html ? ef = gh
其他回答
如果你正在使用Apache 2.4,不需要启用重写Apache模块,你可以使用这样的东西:
# non-www to www
<If "%{HTTP_HOST} = 'domain.com'">
Redirect 301 "/" "http://www.domain.com/"
</If>
使用重写引擎是解决这个问题的重量级方法。这里有一个更简单的解决方案:
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
# real server configuration
</VirtualHost>
然后,您将有另一个<VirtualHost>节,其中ServerName为www.example.com,用于您的真实服务器配置。当使用Redirect指令时,Apache会自动保留/之后的所有内容,这是一个常见的误解,为什么这个方法不起作用(实际上它可以)。
这对我来说很管用:
RewriteCond %{HTTP_HOST} ^(?!www.domain.com).*$ [NC]
RewriteRule ^(.*)$ http://www.domain.com$1 [R=301,L]
在将所有域重定向到www子域时,我使用前瞻性模式(?!www.domain.com)来排除www子域,以避免Apache中的无限重定向循环。
重定向域。TLD到www。
以下行可以添加到Apache指令或.htaccess文件中:
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
其他的子域仍在工作。 不需要调整线条。只需复制/粘贴到正确的位置。
如果你修改了vhost,不要忘记应用apache的变化。
(基于默认的Drupal7 .htaccess,但应该在很多情况下工作)
我发现在使用多个vhost时使用ServerAlias更容易(也更有用)。
<VirtualHost x.x.x.x:80>
ServerName www.example.com
ServerAlias example.com
....
</VirtualHost>
这也适用于https vhosts。