【问题标题】:Can't redirect to https (htaccess)无法重定向到 https (htaccess)
【发布时间】:2018-04-23 09:11:19
【问题描述】:

我试图配置我的 htaccess 文件,该文件将使用以下语句从 http 重定向到 https。但它不能。

注意:我也不希望网站 URL 之前有 www。

我的代码可能有哪些错误。请任何人提出建议。

 RewriteEngine on
 RewriteCond %{HTTPS} off
 RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
 RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,L]

【问题讨论】:

    标签: apache .htaccess http redirect https


    【解决方案1】:

    问题似乎是这一行:

    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    

    此行使此规则仅适用于以 www 开头的域。

    您需要使用以下命令将启动 www 设为可选:

    RewriteEngine on
    
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]
    

    【讨论】:

      【解决方案2】:

      作为另一种解决方案,如果你只有一个域名(www.)example.com,你可以使用更具可读性:

      RewriteEngine on
      RewriteCond %{HTTPS} off [OR]
      RewriteCond %{HTTP_HOST} ^www [NC]
      RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]
      

      【讨论】:

        【解决方案3】:

        尝试以下方法:

         RewriteEngine On
         RewriteCond %{HTTPS} !=on
         RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

        另外,还可以根据端口号进行重定向,例如:

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

        这会将端口 80 上收到的所有请求重定向到 HTTPS。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-11
          • 2021-11-10
          • 2012-12-23
          • 2020-07-11
          • 2016-09-01
          相关资源
          最近更新 更多