Force ssl in codeigniter 3

Easy way to configure for HTTPS (SSL) in Codeigniter 3. redirect http to https

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 (i.e. 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 (i.e. application/hooks) and then create a new file named ssl.php inside the hooks folder (i.e. 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());

Mathod 2

Use and edit this .htaccess file.

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
RH Suman
RH Suman
Articles: 64

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply