我想将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。在url或强制SSL协议中,然后尝试在htaccess文件中使用可能的变体,例如:
RewriteEngine On RewriteBase / ### Force WWW ### RewriteCond %{HTTP_HOST} ^example\.com RewriteRule (.*) http://www.example.com/$1 [R=301,L] ## Force SSL ### RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://example.com/$1 [R,L] ## Block IP's ### Order Deny,Allow Deny from 256.251.0.139 Deny from 199.127.0.259
其他回答
Add
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
在任何其他规则之前。htaccess。
重定向非www到www(均:http + https)
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
试试这个:
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]
RewriteRule ^www\.(.*)$ http://$1 [L,R=301]
如果主机以www开头,我们将整个主机粘贴到URL的开头,然后去掉“www”。
我不知道你为什么要删除www。 但相反的版本是:
# non-www.* -> www.*, if subdomain exist, wont work
RewriteCond %{HTTP_HOST} ^whattimein\.com
RewriteRule ^(.*)$ http://www.whattimein.com/$1 [R=permanent,L]
这个脚本的优点是: 如果你有test.whattimein.com之类的(开发/测试环境) 它不会将U重定向到原始环境。
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ https://%1/$1 [R]
RewriteCond捕获www后HTTP_HOST变量中的所有内容。并将其保存在%1中。
RewriteRule捕获了没有/开头的URL,并将其保存在$1中。