htaccess 重定向非 www http 和 https [英] htaccess redirect for non-www both http and https

查看:30
本文介绍了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 都不会像 http://www.whatever.example.com 那样附加 www.

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]

解释如下:

  1. 第一个条件测试 HTTP 标头字段 Host 是否具有所需的格式(正好包含一个句点).
  2. 第二个条件测试 HTTPS 变量的值(值 onoff)和 s 的连接值(所以 onsoffs)等于 ons 并捕获 s.这意味着如果 %{HTTPS}s 的计算结果为 ons,则第一个匹配组为 s,否则为空.
  3. 该规则将匹配所有请求,因为每个字符串都有一个开头(用 ^ 标记)并将它们重定向到 http%1://www.%{HTTP_HOST} 的评估值%{REQUEST_URI} 如果两个条件都为真.其中 %1 是前一个条件的第一个匹配组(s 如果为 HTTPS,否则为空),%{HTTP_HOST} 是 HTTP 请求的主机%{REQUEST_URI} 是请求的绝对 URL 路径.
  1. The first condition tests if the HTTP header field Host has the required format (contains exactly one period).
  2. The second condition tests if the concatenated value of the value of the HTTPS variable (values on and off) and s (so either ons or offs) is equal to ons and captures the s. This means if %{HTTPS}s evaluates to ons, the first matching group is s and empty otherwise.
  3. The rule will match all requests as every string has a start (marked with ^) and redirects them to the evaluated value of http%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.

这篇关于htaccess 重定向非 www http 和 https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆