我想将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]
但是,有没有一种方法可以在不硬编码域名的通用方式做到这一点呢?
当前回答
Add
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
在任何其他规则之前。htaccess。
其他回答
RewriteEngine on
# if host value starts with "www."
RewriteCond %{HTTP_HOST} ^www\.
# redirect the request to "non-www"
RewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]
如果你想同时删除http和https上的www,请使用以下方法:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]
这种重定向 非ssl
http://www.example.com
to
http://example.com
和 SSL
https://www.example.com
to
https://example.com
在apache 2.4上。*你可以使用一个带有if指令的重定向,
<if "%{HTTP_HOST} =='www.example.com'">
Redirect / http://example.com/
</if>
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]
重定向非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]
更新后可以在Apache 2.4上工作:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
与Michael的唯一变化是删除[NC],这会产生“AH00665”错误:
不支持非正则表达式模式“-f”的NoCase选项,将被忽略
我不知道你为什么要删除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重定向到原始环境。