我想将www.example.com重定向到example.com。下面的htaccess代码可以做到这一点:
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
但是,有没有一种方法可以在不硬编码域名的通用方式做到这一点呢?
我想将www.example.com重定向到example.com。下面的htaccess代码可以做到这一点:
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
但是,有没有一种方法可以在不硬编码域名的通用方式做到这一点呢?
当前回答
WWW到非WWW使用HTTPS
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
其他回答
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
和迈克尔的一样,除了这个有用:P
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ https://%1/$1 [R]
RewriteCond捕获www后HTTP_HOST变量中的所有内容。并将其保存在%1中。
RewriteRule捕获了没有/开头的URL,并将其保存在$1中。
试试这个:
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]
RewriteRule ^www\.(.*)$ http://$1 [L,R=301]
如果主机以www开头,我们将整个主机粘贴到URL的开头,然后去掉“www”。
如果.htaccess定制不是理想的选择:
我创建了简单的重定向服务器供公众使用。只需添加A或CNAME记录:
CNAME r.simpleredirect.net
A 89.221.218.22
更多信息:https://simpleredirect.net
但是如果我们需要为单独的http和https这样做:
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]