【问题标题】:Forcing HTTPS on Apache with strange results在 Apache 上强制使用 HTTPS,结果很奇怪
【发布时间】:2017-11-20 21:47:03
【问题描述】:

我刚刚为我的网站购买了 SSL 证书,我正在尝试强制使用 HTTPS。它有点工作,但不是真的。我在 Apache 上使用 PHP Slim 框架进行自定义路由。

我的文件夹结构

root/
   .htaccess (A)
   php/
   public_html/
     .htaccess (B)

.htaccess (A)

我的主 htaccess 文件有这些规则

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

当我转到example.com 时,它会转到安全页面。太好了!

.htaccess (B)

我的 public_html 文件有这些规则

<IfModule mod_rewrite.c>
    RewriteEngine on
    #RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.php [QSA,L]
</IfModule>


# Always use https for secure connections
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

问题:

如果我去http://www.example.com/login

而不是重定向到https://www.example.com/login

它重定向到https://www.example.com/index.php

【问题讨论】:

  • 那是因为您的 htaccess 中有 组规则。 &lt;IfModule mod_rewrite.c&gt; 中的第一条规则检查请求的文件是否存在,如果不存在,则重定向到 index.php。由于/login 可能不作为真实文件存在,因此将触发该规则。只需将您的 https-check 移到另一条规则之前。
  • 已将其添加为答案,因此您可以接受并关闭问题。

标签: php apache .htaccess ssl mod-rewrite


【解决方案1】:

htaccess-files 中的规则从上到下进行验证。在您的 htaccess 中,它首先检查服务器上是否存在请求的资源 (/login)。如果没有,它会将请求重定向到 index.php。

如果您只是将 https-check/redirect 移到其他规则之前 ,它应该可以工作。

<IfModule mod_rewrite.c>
    RewriteEngine on
    #RewriteBase /

    # Always use https for secure connections
    RewriteCond %{SERVER_PORT} 80
    RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

    # Redirect requests to non existing resources to index.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.php [QSA,L]
</IfModule>

我还删除了第二个RewriteEngine On。一次就够了。

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 2018-03-11
    • 2013-11-03
    • 2016-10-31
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2020-06-11
    • 2021-02-19
    相关资源
    最近更新 更多