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

我错过了什么?


当前回答

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>

试试这个:

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

要从你的URL网站中删除www,请在。htaccess文件中使用以下代码:

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

要在你的网站URL中强制使用。htaccess上的这段代码

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^YourSite.com$
RewriteRule ^(.*)$ http://www.yourSite.com/$1 [R=301]
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule ^(([^/]+/)*[^./]+)$ /$1.html [R=301,L]

YourSite.com必须替换为您的URL。

要将所有直接发送到域名www的请求重定向到301,您可以使用:

RewriteEngine On

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

这样做的好处是,如果你有任何有效的子域,这将工作。

example.com重定向到www.example.com

没有重定向

没有重定向

如果使用上述两个<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

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