htaccess的重定向非www HTTP和HTTPS
问题描述:
我想有:
-
http://example.com
重定向到:http://www.example.com
-
https://example.com
重定向到:https://www.example.com
-
http://example.com
redirect to:http://www.example.com
-
https://example.com
redirect to:https://www.example.com
和任何的 http://whatever.example.com
不追加了www喜欢的http://www.whatever.example。 COM
。
And anything that is http://whatever.example.com
NOT append the www like http://www.whatever.example.com
.
答
试试这个规则:
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
下面是一个解释:
- 在第一个条件测试,如果HTTP头字段的主机的具有要求的格式(只包含一个周期)。
- 第二个条件测试,如果值的串联值的 HTTPS 的变量(值
在
和关闭
)和取值
(所以无论是附件
或取舍
)等于附件
并捕获取值
。这意味着,如果%{HTTPS}等
的计算结果为附件
,第一个匹配的组取值
空,否则。 - 在该规则将匹配所有的请求,因为每个字符串有一个开始(标有
^
),并将其重定向到HTTP%1的评估值://www.% {HTTP_HOST}%{REQUEST_URI}
如果这两个条件都满足。其中,%1
是第一个匹配的组的previous条件(取值
如果HTTPS和空否则)%{HTTP_HOST}
是HTTP的主机的要求和%{REQUEST_URI}
是被请求的绝对URL路径。
- The first condition tests if the HTTP header field Host has the required format (contains exactly one period).
- The second condition tests if the concatenated value of the value of the HTTPS variable (values
on
andoff
) ands
(so eitherons
oroffs
) is equal toons
and captures thes
. This means if%{HTTPS}s
evaluates toons
, the first matching group iss
and empty otherwise. - The rule will match all requests as every string has a start (marked with
^
) and redirects them to the evaluated value ofhttp%1://www.%{HTTP_HOST}%{REQUEST_URI}
if both conditions are true. Where%1
is the first matching group of the previous condition (s
if HTTPS and empty otherwise),%{HTTP_HOST}
is the HTTP Host of the request and%{REQUEST_URI}
is the absolute URL path that was requested.