【问题标题】:How can I direct all folders on my website to use HTTPS in .htaccess?如何指示我网站上的所有文件夹在 .htaccess 中使用 HTTPS?
【发布时间】:2021-04-08 16:22:06
【问题描述】:

请客气,这是我在这里的第一个问题:)

我的设置

Apache 在我的 Raspberry Pi 4 上提供服务

我的 .htaccess 文件

# Force HTTPS on all pages
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

问题

输入“tyler.cloud”成功重定向到https://www.tyler.cloud,但输入“tyler.cloud/react”停留在http://tyler.cloud/react(不是HTTPS)。

我在上面尝试过的结果相同

RewriteEngine on
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

以及其他一些变体。

【问题讨论】:

    标签: apache .htaccess ssl https


    【解决方案1】:

    原来 /var/www 中的“AllowOverride”必须是 /etc/apache2/apache2.conf 中的“All”。

    它被设置为“无”,这意味着它忽略了我所有的 .htaccess 文件。

    我用过这个:

    RewriteEngine On
    RewriteCond %{HTTPS} !on
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    

    它似乎有效!

    【讨论】:

      【解决方案2】:

      考虑使用 apache2.conf 而不是 .htaccess。因为在您具有 root 访问权限的服务器中使用 .htaccess 是一个坏主意。它可能会不必要地减慢您的网站速度。

      尝试使用它而不是 .htaccess:

      <Directory "/path/to/web/directory">
      RewriteEngine On
      RewriteCond %{HTTPS} !on
      RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
      </Directory>
      

      如果您使用的是 VirtualHosts,请添加:

      RewriteEngine On
      RewriteOptions Inherit
      

      在虚拟主机内。

      而且,如果有人将他们的域指向您的 IP 地址,那么他们将能够通过他们的 IP 地址显示您的网站(除非您使用基于名称的虚拟主机,即 https://httpd.apache.org/docs/2.4/vhosts/name-based.html,但他们仍然能够当然,使用 IP 地址访问您的主要 Apache 主机)。虽然因为您使用的是 HTTPS,但他们的域可能会失败 HTTPS。但是,由于您没有设置 HSTS (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security),用户仍然可以访问该网站。

      因此,如果域与 https://www.tyler.cloud 不匹配,我还建议您重定向到您的域,使用以下内容:(将以下内容添加到 &lt;Directory&gt; 指令中)

      (如果您打算添加 HSTS 预加载,请参阅下一个解决方案)

      #Do not use RewriteEngine On more than once. see the next solution if you are planning to use HSTS preload
      RewriteCond %{HTTP_HOST} !^www\.tyler\.cloud [OR]
      RewriteCond %{HTTPS} !=on
      RewriteRule ^ https://www\.tyler\.cloud%{REQUEST_URI} [R=301,L]
      

      如果计划使用 HSTS 预加载,请使用下一个解决方案:

      RewriteCond %{HTTP_HOST} ^tyler\.cloud
      RewriteCond %{HTTPS} !=on
      RewriteRule ^ https://tyler\.c%{REQUEST_URI} [R=301,L]
      
      RewriteCond %{HTTP_HOST} !^www\.tyler\.cloud [OR]
      RewriteCond %{HTTPS} !=on
      RewriteRule ^ https://www\.tyler\.cloud%{REQUEST_URI} [R=301,L]
      

      你很高兴!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-19
        • 2018-03-19
        • 1970-01-01
        • 2020-06-29
        • 2018-11-09
        • 2019-09-07
        • 2015-10-19
        • 2017-11-18
        相关资源
        最近更新 更多