如何在codeigniter中强制ssl?

9 php ssl codeigniter

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

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

Rab*_*ong 28

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

$config['enable_hooks'] = TRUE;
Run Code Online (Sandbox Code Playgroud)

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

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

现在创建一个名为文件夹hooks内的新目录application(即application/hooks),然后ssl.php在hooks文件夹中创建一个名为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());
    }
}
Run Code Online (Sandbox Code Playgroud)


fus*_*aki 22

  1. 更改base_url您的配置:

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

    RewriteCond %{HTTPS} off
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    Run Code Online (Sandbox Code Playgroud)