php.htaccesscodeigniterssl

Forcing SSL in codeigniter with a helper


I am trying to adopt a ssl routing solution to my shopping cart app so that certain pages are "forced" to be https:// pages and visa-verse. Through research I have come across many solutions which involve the use of code either in a helper, a hook or in a controller. I have tried a few of these solutions and in each, I get a redirect error when switching to an https:// page.

Here is the last version I have tried (found here: http://nigel.mcbryde.com.au/2009/03/working-with-ssl-in-codeigniter):

Create a file in application/helper called ssl_helper.php

if (!function_exists('force_ssl'))
{
    function force_ssl()
    {
        $CI =& get_instance();
        $CI->config->config['base_url'] =
                 str_replace('http://', 'https://',
                 $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] != 443)
        {
            redirect($CI->uri->uri_string());
        }
    }
}

function remove_ssl()
{
    $CI =& get_instance();
    $CI->config->config['base_url'] =
                  str_replace('https://', 'http://',
                  $CI->config->config['base_url']);
    if ($_SERVER['SERVER_PORT'] != 80)
    {
        redirect($CI->uri->uri_string());
    }
}

Load the helper, then in the constructor for any controller that requires ssl, simply insert:

force_ssl();

In every controller that you don’t want to have ssl put:

if (function_exists('force_ssl')) remove_ssl();

As stated above, when using this, I get stuck in a redirect loop and get an error (though the url has the https:// as it should). Could my problem be in my .htaccess file? Here is my .htaccess file:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /store
   RewriteCond $1 !^(index.php\.php|resources|robots\.txt)
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^(.*)$ index.php?/$1 [QSA,L]
</IfModule>

I've been at this for over a week now! Any suggestions?


Solution

  • I answered a similar question here: https://stackoverflow.com/questions/1500527/how-to-use-ssl-with-codeigniter/1500558#1500558

    But, in a nutshell:

    <IfModule mod_rewrite.c>
       RewriteEngine On
       RedirectPermanent /sslfolder https://www.yoursite.com/sslfolder
    </IfModule>