简体   繁体   中英

How to force ssl in codeigniter?

I am using codeigniter 3. How do I force SSL connection to my web pages so that all the pages are loaded with the green padlock icon beside it?

Note: How can I do this without having to edit htaccess file ?

Open config file from location application/config/config.php and enable or set hooks to true like this:

$config['enable_hooks'] = TRUE;

Then create a new file named hooks.php inside the config folder (ie application/config/hooks.php) and add the following code in it:

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

Now create a new directory named hooks inside the application folder (ie application/hooks) and then create a new file named ssl.php inside the hooks folder (ie application/hooks/ssl.php).

Add the following code in the ssl.php file:

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());
    }
}
  1. Change base_url in your config:

     $config['base_url'] = 'https://www.my-site.com/';
  2. Provide a certificate for your secure connection
  3. Redirect incoming traffic from http to https :

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

Codeigniter(GAE) : best practice to redirect http to https in the ssl.php file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM