我有一个网站,似乎不能从非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] 

我错过了什么?


当前回答

我发现在使用多个vhost时使用ServerAlias更容易(也更有用)。

<VirtualHost x.x.x.x:80>
    ServerName www.example.com
    ServerAlias example.com
    ....
</VirtualHost>

这也适用于https vhosts。

其他回答

<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

<VirtualHost *:80>
    ServerAlias example.com
    RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>

如果使用上述两个<VirtualHost *:80>块的解决方案,具有不同的ServerNames…

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
    ServerName www.example.com
</VirtualHost>

... 那么你必须设置NameVirtualHost On。

如果你不这样做,Apache不允许自己使用不同的servername来区分块,所以你会得到这个错误消息:

[warn] _default_ VirtualHost overlap on port 80, the first has precedence

…或者没有重定向发生,或者有一个无限重定向循环,这取决于你先放哪个块。

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

This starts with the HTTP_HOST variable, which contains just the domain name portion of the incoming URL (example.com). Assuming the domain name does not contain a www. and matches your domain name exactly, then the RewriteRule comes into play. The pattern ^(.*)$ will match everything in the REQUEST_URI, which is the resource requested in the HTTP request (foo/blah/index.html). It stores this in a back reference, which is then used to rewrite the URL with the new domain name (one that starts with www).

[NC]表示不区分大小写的模式匹配,[R=301]表示使用代码301进行外部重定向(资源永久移动),[L]停止所有进一步重写,并立即重定向。

如果你正在使用Apache 2.4,不需要启用重写Apache模块,你可以使用这样的东西:

# non-www to www
<If "%{HTTP_HOST} = 'domain.com'">
  Redirect 301 "/" "http://www.domain.com/"
</If>