我有一个网站,似乎不能从非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]
我错过了什么?
当前回答
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]停止所有进一步重写,并立即重定向。
其他回答
我也有同样的问题。 但是用这个解决了
RewriteEngine上 重写HTTP_HOST} ! RewriteRule ^ (. *) http://www.% {HTTP_HOST} / 1美元(R = 301 L)
将non-www重定向到www。
这个规则将www重定向到非www
RewriteEngine上 ^my-domain\.com$ [NC] RewriteRule ^ (. *) http://my-domain.com/ 1美元(R = 301 L)
参考http://dense13.com/blog/2008/02/27/redirecting-non-www-to-www-with-htaccess/
这是我自己网站的配置,工作起来很有魅力。
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin admin@domain.com
ServerName www.domain.com
ServerAlias domain.com
DocumentRoot /var/www/html/domain
<Directory /var/www/html/domain/>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# Redirect non-www to www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/domain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/domain.com/privkey.pem
</VirtualHost>
</IfModule>
我在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]
这与许多其他建议类似,只是做了一些增强:
不需要硬编码域(适用于接受多个域或环境之间的vhosts) 保留方案(http/https),忽略前面%{REQUEST_URI}规则的影响。 路径部分不受%{REQUEST_URI}等先前rewriterrules的影响。 重写HTTP_HOST} !(数控) RewriteRule ^(.*)$ %{ REQUEST_SCHEME}: / / www. % {HTTP_HOST} / 1美元(R = 301 L)
重定向域。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,但应该在很多情况下工作)