【问题标题】:Redirect only FQDN and www. to HTTPS仅重定向 FQDN 和 www。到 HTTPS
【发布时间】:2014-08-20 09:53:31
【问题描述】:

目前我有以下 RewriteRules 可以将用户重定向到 HTTPS:

# Force all request to HTTPS URLs                                                    
RewriteCond %{HTTP:X-Forwarded-Proto} !https                                         
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=302,L]

虽然它会重定向所有流量,但我希望它只对 FQDN 和 www 这样做。超域。

所以重定向:

  • example.org
  • www.example.org

不被重定向的例子:

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

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

【问题讨论】:

    标签: .htaccess mod-rewrite redirect


    【解决方案1】:

    您可以添加此条件:RewriteCond %{HTTP_HOST} ^(www\.)?example\.org$ [NC].
    这将仅匹配 example.orgwww.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]
    

    【讨论】:

    • 在不对域进行硬编码的情况下这样做吗?
    • 没有什么是不可能的。是的,它可以按照你想要的方式完成,但它会使代码复杂一点。为什么要避免对域进行硬编码?有什么原因吗?
    • 它将作为解决方案的基本安装的一部分出现,该解决方案将由各方在不同的硬件/操作系统上部署,因此能够删除编辑此步骤会很好。
    • 在这种情况下,我们应该反过来解决问题。我的意思是,我们将用异常重定向检查替换域检查。你可以看到我编辑过的答案
    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    相关资源
    最近更新 更多