.htaccess 仅将FQDN和www.重定向到HTTPS

.htaccess 仅将FQDN和www.重定向到HTTPS,.htaccess,mod-rewrite,redirect,.htaccess,Mod Rewrite,Redirect,目前,我有以下规则将用户重定向到HTTPS: # Force all request to HTTPS URLs RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=302,L]

目前,我有以下规则将用户重定向到HTTPS:

# Force all request to HTTPS URLs                                                    
RewriteCond %{HTTP:X-Forwarded-Proto} !https                                         
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=302,L]
虽然它重定向了所有流量,但我希望它只对FQDN和www.sudomain这样做

因此,重定向:

  • example.org
  • www.example.org
不重定向的示例:

  • example.example.org
  • www.example.example.org
  • blog.example.org

要做到这一点,我需要添加哪些
RewriteCond
语句?

您可以添加以下条件:
RewriteCond%{HTTP\u HOST}^(www\)?example\.org$[NC]

这将仅与
example.org
www.example.org
匹配

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(www\.)?example\.org$ [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=302,L]

编辑:避免在规则中使用域名(这意味着使用例外子域)


在没有硬编码的情况下,有没有办法做到这一点?没有什么是不可能的。是的,它可以按照您想要的方式完成,但这会使代码更加复杂。为什么要避免硬编码域?有什么原因吗?它将作为解决方案基础安装的一部分出现,该解决方案将由各方在不同的硬件/操作系统上部署,因此最好能够删除编辑该解决方案的步骤。在这种情况下,我们应该反过来处理问题。我的意思是,我们将用异常替换域检查,使之成为重定向检查。你可以看到我编辑的答案
RewriteEngine On

# if subdomain exception do nothing
RewriteCond %{HTTP_HOST} ^(example|www\.example|blog)\. [NC]
RewriteRule . - [L]

# if we reach here, that means we have www.example.org or example.org so redirect if not https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=302,L]