【问题标题】:How to redirect index.php to HTTPS only?如何仅将 index.php 重定向到 HTTPS?
【发布时间】:2017-06-29 16:00:22
【问题描述】:

这个问题已经被问过很多次了,但我尝试了很多不同的变体,但都没有成功 - 以下是我尝试过的和得到的示例:

Gives 500 Internal Server Error:
<Location /index.php>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</Location>

Gives TOO MANY REDIRECTS
RewriteEngine On
RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Gives TOO MANY REDIRECTS
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^index\.php$ https://foo.bar [L,R=301]

Gives TOO MANY REDIRECTS
<?php
if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}
?>

我无法使用这些方法中的任何一种使 HTTPS 重定向正常工作。

我试图仅在用户访问时强制 index.php 重定向到 HTTPS

http://foo.bar(包括斜杠)

http://foo.bar/index.php

【问题讨论】:

  • SSL 是如何管理的?您是否在服务器上直接安装了证书,或者您是否使用某种前端代理?您的最后两个结果暗示后者。

标签: php .htaccess https


【解决方案1】:

这对我来说非常适合:

RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

【讨论】:

  • 这仍然提供了太多的重定向
  • index.php 是否有任何代码进行重定向?听起来好像存在重定向循环问题。
【解决方案2】:

我建议在每个文件的顶部实现这个 PHP 代码:

if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
    $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}

HTTP 响应状态码 301 Moved Permanently 用于 永久 URL 重定向,意味着当前链接或记录使用 应更新收到响应的 URL。新网址 应在响应中包含的位置字段中提供。 301 重定向被认为是升级用户的最佳实践 从 HTTP 到 HTTPS。

【讨论】:

    【解决方案3】:

    500 内部服务器归因于您在 htaccess 中使用的 Location 指令。位置指令仅在服务器配置 contaxt 中使用。 要将 index.php 重定向到 https,您可以使用以下规则。我假设您使用的是 apache 2.4 或更高版本。

    RewriteEngine on
    RewriteCond %{REQUEST_SCHEME} http$
    RewriteRule ^index\.php$ https://example.com [L,R]
    

    在测试此规则之前清除浏览器缓存。

    对于较低版本的 apache,您可以将 Condition 行替换为以下之一:

    RewriteCond %{HTTPS} off
    
    RewriteCond %{SERVER_PORT} 80 
    

    【讨论】:

      【解决方案4】:

      你可以使用:

      RewriteEngine On
      RewriteCond %{HTTPS} off
      RewriteRule ^(index\.php)?$ https://%{HTTP_HOST} [R=301,NC]
      

      它适用于: http://foo.bar -> https://foo.bar
      http://foo.bar/index.php -> https://foo.bar
      但不是http://foo.bar/other

      【讨论】:

        【解决方案5】:

        好的,我在我的网站上面临同样的问题我的网站在 Joomla 3.5 我正在使用下面的代码。它在我的 Joomla 中正常工作! 3.5.1。

        RewriteEngine On 
        RewriteCond %{HTTP_HOST} !^www\. [NC]
        RewriteRule ^(.*)$ http://www.yourdomain.ac.in/$1 [L,R=301]
        RewriteCond %{HTTPS} off
        RewriteRule ^(.*)$ https://www.yourdomain.ac.in/$1 [L,R=301] 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-11
          • 1970-01-01
          • 2018-04-15
          • 1970-01-01
          • 2018-10-03
          相关资源
          最近更新 更多