【问题标题】:PHP (CodeIgniter) 301 redirect http to httpsPHP (CodeIgniter) 301 将 http 重定向到 https
【发布时间】:2018-12-26 13:14:06
【问题描述】:

如果网站有 SSL 证书,我会尝试强制使用 https。我可以确认代码确实有效,因为它确实进行了重定向,但它最终无限循环,尽管我不知道为什么。仅当服务器端口不是 443 时才应进行重定向,并且我假设在第一次重定向之后,用户应该使用端口 443。

这是我的代码;

// If they're using a masking domain and they own an SSL certificate, force SSL

    $this->db->where('client_id', $client['client']);
    $result = $this->db->get('ssl_certs')->row_array();

    // only run this function if there is a date in this field

    if (!empty($result['ssl_completed_date']))
    {
        // if they're not using https, redirect them to https

        if($_SERVER['SERVER_PORT'] != 443)
        {
            $redirect = 'https://www.' . $_SERVER['HTTP_HOST'] . '/website';
            header('HTTP/1.1 301 Moved Permanently');
            header('Location: ' . $redirect);
            exit();
        }
    }

任何帮助将不胜感激!

【问题讨论】:

    标签: php codeigniter redirect server


    【解决方案1】:

    需要注意的几点:

    1) 我相信返回的值是一个字符串,而不是一个数字。 (未检查 - 但需要验证)。无论如何它不会有什么不同,因为你不是在做 !== 而是放松的 !=

    2)手册,在“server_port”(http://php.net/manual/en/reserved.variables.server.php)状态下

    注意:在 Apache 2 下,您必须设置 UseCanonicalName = On,以及 UseCanonicalPhysicalPort = On 才能获取物理(真实)端口,否则,此值可能会被欺骗,它可能会或可能不会返回物理端口端口值。在依赖于安全的上下文中依赖此值是不安全的。

    3) 最好使用 $_SERVER 数组的“HTTPS”。同一页面上的详细信息。

    4) 如果在负载均衡器后面,您还需要检查$_SERVER['HTTP_X_FORWARDED_PROTO']

    if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
        $isSecure = ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
    } else {
        $isSecure = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] == 1));
    }
    

    【讨论】:

    • 感谢罗比的详细解释!我将检查 SERVER_PORT 更改为 HTTP_X_FORWARDED_PROTO 并且它起作用了。
    • 好东西。添加以上两个,然后您的脚本在负载均衡器或直接运行(以防您在另一个站点上重复使用)。很高兴它正在工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2018-10-19
    • 2017-12-13
    • 2015-06-23
    • 2018-05-03
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多