我有一个网站,似乎不能从非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]
我错过了什么?
当前回答
我发现在使用多个vhost时使用ServerAlias更容易(也更有用)。
<VirtualHost x.x.x.x:80>
ServerName www.example.com
ServerAlias example.com
....
</VirtualHost>
这也适用于https vhosts。
其他回答
这与许多其他建议类似,只是做了一些增强:
不需要硬编码域(适用于接受多个域或环境之间的vhosts) 保留方案(http/https),忽略前面%{REQUEST_URI}规则的影响。 路径部分不受%{REQUEST_URI}等先前rewriterrules的影响。 重写HTTP_HOST} !(数控) RewriteRule ^(.*)$ %{ REQUEST_SCHEME}: / / www. % {HTTP_HOST} / 1美元(R = 301 L)
如果你只想加载www的https版本,在apache虚拟主机文件中使用下面的配置。所有这些都可以放在一个文件中。
重定向所有HTTP到www的HTTPS:
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
Redirect permanent / https://www.example.com/
</VirtualHost>
重定向HTTPS非www到HTTPS www:
<VirtualHost *:443>
ServerName example.com
Redirect permanent / https://www.example.com/
</VirtualHost>
实服务器配置
<VirtualHost *:443>
ServerAdmin hostmaster@example.com
DocumentRoot "/path/to/your/sites/.htaccess-file-folder"
SetEnv APPLICATION_ENV "production"
<Directory "/path/to/your/sites/.htaccess-file-folder">
Options Indexes FollowSymLinks
DirectoryIndex index.php index.html
AllowOverride All
Order allow,deny
Allow from all
</Directory>
ServerName www.example.com
SSLEngine ON
SSLCertificateFile "/path/to/your/example.cert.pem"
SSLCertificateKeyFile "/path/to/your/example.key.pem"
ErrorLog /path/to/your/example.com-error.log
CustomLog /path/to/your/example.com-access.log combined
#Your other configurations if you have
</VirtualHost>
试试这个:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*) http://www.example.com$1 [R=301]
不要总是使用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 -规范主机名
我在WP Multisite上有一个类似的任务,其中重定向规则必须是通用的(对于我添加到网络中的任何给定域)。我首先解决了向域(停放的域)添加通配符。注意。com之后。
CNAME * domain.com.
然后我在我的多站点根目录下的.htaccess文件中添加了以下代码行。我想它适用于任何网站。
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
希望这能有所帮助。
ps.如果你想从not www重定向到www,把最后一行改为
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]