Always redirect to HTTPS with Codeigniter

Asked

Viewed 1,934 times

0

I have an application with Codeigniter and always need to force the connection redirect to https.

I did it this way:

  1. I changed inside config\config.php the line $config['enable_hooks'] for TRUE.
  2. Within config\hooks.php added the lines.

    $hook['post_controller_constructor'][] = array(
        'function' => 'redirect_ssl', 
        'filename' => 'ssl.php', 
        'filepath' => 'hooks'
    );
    
  3. In the folder hooks created the file ssl.php with the following function:

    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());
        }
    }
    

After testing the page up and redirected to https:// more comes Chrome error:

This page is not working
Excessive redirection per meusite.com Try to clear the cookies. ERR_TOO_MANY_REDIRECTS`

  • 1

    This type of redirection can be done directly by the dns server instead of by the code, in cloudflare in Crypto > Always use HTTPS you can configure to do this automatic redirection, I know it does not solve your problem, but it serves as a possible option.

  • I’m with the cloudflare. And it’s not doing automatico.

  • 1

    by default it does not redirect, have to change the settings in the Crypto tab

  • 1

    I don’t believe it. It worked. kkkk I didn’t know this function. In base_url now I just need to force the exchange of http for https.

1 answer

1

  • I will test by file then. A which point of view would be safer?

  • I will improve the text.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.