【问题标题】:How to force ssl in codeigniter?如何在codeigniter中强制使用ssl?
【发布时间】:2017-03-06 12:01:21
【问题描述】:

我正在使用 codeigniter 3。如何强制 SSL 连接到我的网页,以便所有页面加载时旁边都有绿色挂锁图标?

注意:如何在不编辑 htaccess 文件的情况下执行此操作?

【问题讨论】:

  • 构造函数用于加载用户定义的帮助器: public function __construct() { parent::__construct(); $this->load->helper(array('ssl_helper')); force_ssl();并创建一个文件名为 ssl_helper.php 的辅助函数: function force_ssl() { if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") { $url = “https://”。 $_SERVER['SERVER_NAME'] 。 $_SERVER['REQUEST_URI'];重定向($url);出口; } } 同时在 config.php 中启用助手。否则,使用 htaccess 控制器可能无法工作,您也可以加载外部图标

标签: php codeigniter ssl


【解决方案1】:

从位置 application/config/config.php 打开配置文件并启用或设置挂钩为 true,如下所示:

$config['enable_hooks'] = TRUE;

然后在config文件夹(即application/config/hooks.php)中创建一个名为hooks.php的新文件,并在其中添加以下代码:

$hook['post_controller_constructor'][] = array(
    'function' => 'redirect_ssl',
    'filename' => 'ssl.php',
    'filepath' => 'hooks'
);

现在在application 文件夹内创建一个名为hooks 的新目录(即application/hooks),然后在hooks 文件夹内创建一个名为ssl.php 的新文件(即application/hooks/ssl.php) .

ssl.php文件中添加如下代码:

function redirect_ssl() {
    $CI =& get_instance();
    $class = $CI->router->fetch_class();
    $exclude =  array('client');  // add more controller name to exclude ssl.
    if(!in_array($class,$exclude)) {
        // redirecting to ssl.
        $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
    } else {
        // redirecting with no ssl.
        $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
    }
}

【讨论】:

  • 我已经尝试过了。但 ssl 仍然显示不安全。这是为什么呢?
  • @TriMurvianto 检查页面源中的不安全元素,例如使用 http 加载的图像、使用完整路径硬编码 http 而不是 https 的脚本
  • 在哪里添加 cert filekey file 在 codeigniter 中?以及 c 将如何访问它?
  • 当我使用 HTTP 运行时,请求正文丢失
  • 此解决方案适用于我的情况,但请确保在 config.php 中设置基本 url $config['base_url']='https://example.com' .
【解决方案2】:
  1. 在您的配置中更改base_url

    $config['base_url'] = 'https://www.my-site.com/';
    
  2. 为您的安全连接提供证书
  3. 将传入流量从http 重定向到https

    RewriteCond %{HTTPS} off
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    

【讨论】:

  • 这是迄今为止最简单和最好的解决方案恕我直言。当我使用常用​​的 htaccess 文件时,我有一个网站不正常。原来原作者没有明确设置基本网址。
  • @fustaki 能否请您详细说明第 2 步。在哪里提供 CI 中的证书。
  • @NomanJaved:证书通常通过您的网络面板设置,网络服务器(通常是 Apache)将处理所有细节; CodeIgniter 通常与此无关。
【解决方案3】:

Codeigniter(GAE):在 ssl.php 文件中将 http 重定向到 https 的最佳实践:

function force_ssl() {
    $server=$_SERVER["SERVER_NAME"];
    $uri=$_SERVER["REQUEST_URI"];
    if ($_SERVER['HTTPS'] == 'off') {
        redirect("https://{$server}{$uri}");
    }
}

【讨论】:

    猜你喜欢
    • 2012-07-14
    • 2019-04-12
    • 2012-07-13
    • 1970-01-01
    • 2013-03-13
    • 2012-01-26
    • 2012-09-09
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多