Search code examples
httphttpscodeigniter-urlcodeigniter-routing

Need https only for the particular pages in codeigniter


By browing i come to know the below code will make us to redirect few pages with https url. Below is the code i am sharing

RewriteEngine on

RewriteCond %{SERVER_PORT} 80 
RewriteCond %{REQUEST_URI} controller/function
RewriteRule ^(.*)$ https://www.yourdomain.com/controller/function[R=301,L]

RewriteCond %{SERVER_PORT} 443 
RewriteCond %{REQUEST_URI} controller/function
RewriteRule ^(.*)$ https://www.yourdomain.com/controller/function[R=301,L]

RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L] 

Now my questions is there is a controller called authenticate.php, there are so many functions in authenticate file like forgot password, login, register, etc. i dont to write like the above code for each and every function. I want to to that htaccess code which is applicable for all the functions in single shot. Can any one share answer for this !!!!!!


Solution

  • I don't use htaccess for this purpose. I use hooks in codeigniter as described in this blog post

    You would have to set in $ssl array the controllers you want to be forced to use ssl, in $partials array the ones you don't care (you might want them to serve both http and https as described in the blog post), and the rest would be forced to use http.

    For your specific pattern which is controller/function you could change the function of check_ssl() to

    function check_ssl()
    {
        $CI =& get_instance();
        $class = $CI->router->fetch_class();
        #method = $CI->router->fetch_method();
    
        $ssl = array('controller/function');
        $partial =  array('login','registration');
    
        if(in_array("$class/$method", $ssl)) {
            force_ssl();
        } else if(in_array($class,$partial)) {
           return;
        } else {
           unforce_ssl();
        }
    }
    

    if you don't want partials you can cooment that part out. If you don't want the rest of the controllers to use http only you replace unforce_ssl() with return;