我有一个网站,似乎不能从非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]
我错过了什么?
当前回答
如果你有多个域名(可选)
-如果所有这些域名都使用https(因为他们应该)
-如果你想让所有的域名都使用www。domainName
这将避免doble重定向(http://non www到http://www,然后到https://www)
<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(.*)$ https://www.%1$1 [R=301,L]
</VirtualHost>
And
<VirtualHost *:443>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>
您应该将重定向代码301更改为最方便的代码
其他回答
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]停止所有进一步重写,并立即重定向。
使用重写引擎是解决这个问题的重量级方法。这里有一个更简单的解决方案:
<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会自动保留/之后的所有内容,这是一个常见的误解,为什么这个方法不起作用(实际上它可以)。
不要总是使用Redirect permanent(或者为什么将来会出现问题)
如果以后有机会添加子域,不要使用永久重定向。
因为如果客户端使用了一个没有注册为VirtualHost的子域,他可能永远也不会到达这个子域,即使后来注册了。
重定向永久发送一个HTTP 301永久移动到客户端(浏览器),他们中的许多人永远缓存这个响应(直到缓存被[手动]清除)。因此,使用该子域将始终自动重定向到www.***,而无需再次请求服务器。
请参阅浏览器缓存HTTP 301多长时间?
使用重定向
<VirtualHost *:80>
ServerName example.com
Redirect / http://www.example.com/
</VirtualHost>
Apache.org -何时不使用mod_rewrite
Apache.org -规范主机名
这很简单!
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
这与许多其他建议类似,只是做了一些增强:
不需要硬编码域(适用于接受多个域或环境之间的vhosts) 保留方案(http/https),忽略前面%{REQUEST_URI}规则的影响。 路径部分不受%{REQUEST_URI}等先前rewriterrules的影响。 重写HTTP_HOST} !(数控) RewriteRule ^(.*)$ %{ REQUEST_SCHEME}: / / www. % {HTTP_HOST} / 1美元(R = 301 L)