首页 > 解决方案 > 使用 .htaccess 强制 SSL + www + 子目录

问题描述

我有以下域:

http://example.net    -> https://www.example.com/
http://example.org    -> https://www.example.com/
http://example.com    -> https://www.example.com/
http://theexample.com -> https://www.example.com/

我正在寻找一种能够强制将所有这些域重定向到使用wwwhttps包括所有子目录的单个域的方法。主域是example.com,我需要重定向它,包括子目录,例如:

http://example.net/blog     -> https://www.example.com/blog
http://www.example.org/blog -> https://www.example.com/blog
https://example.com/blog    -> https://www.example.com/blog
http://theexample.com/blog  -> https://www.example.com/blog

https://www和域example.com是强制性的所有子目录。

预先感谢您的帮助

标签: apache.htaccess

解决方案


与其检查要重定向的主机名,不如检查方案 + 主机名是否不是规范的,然后重定向到它。因此,如果请求不是针对https://www.example.com/...然后重定向(复制 URL 路径)。

例如:

RewriteEngine On

RewriteCond %{HTTPS} =off [OR]
RewriteCond %{HTTP_HOST} !=www.example.com
RewriteRule (.*) https://www.example.com/$1 [R=302,L]

上述状态......对于所有 HTTPSoff或者不是HTTPS 的请求,www.example.com然后重定向到https://www.example.com/<URL-path>. $1是对RewriteRule 模式中捕获子组的反向引用(即 URL 路径)。默认情况下,还会复制任何查询字符串。

CondPattern上的=前缀使其成为精确的字符串匹配,而不是正则表达式。并且前缀否定了正则表达式(即匹配)。!


推荐阅读