If you have a website with HTTP and have an AutoSSL or purchased the SSL for your site, it’s hard to manage redirection because every request to your site has HTTP before any request.
For Codigniter 3
You can redirect your every request from HTTP to HTTPS in Codeigniter 3 using hook Only 3 steps are given below:
1. Enable hook from config.php file
File Path: PROJECT_DIRETORY/application/config/config.php
$config['enable_hooks'] = TRUE;
Note: Set $config['index_page'] to blank string else it will redirect to yourdomain/index.php
$config['index_page'] = 'index.php'; ==> $config['index_page'] = '';
2. Create a new file named hooks.php in config Folder
File Path: PROJECT_DIRETORY/application/config/hooks.php
and add below code in hooks.php
$hook['post_controller_constructor'][] = array(
'function' => 'redirect_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks'
);
3. Then create a new directory with named “hooks” under application directory and then create new file named “ssl.php” in “application/hooks/ssl.php” and add below code to "ssl.php" Directory Path: PROJECT_DIRETORY/application/hooks
File Path: PROJECT_DIRETORY/application/hooks/ssl.php
File Path: PROJECT_DIRETORY/application/hooks/ssl.php
function redirect_ssl() {
$CI =& get_instance();
$class = $CI->router->fetch_class();
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443){
redirect($CI->uri->uri_string());
}
}
if you want to exclude some controllers from HTTPS redirection then use below code function
function redirect_ssl() {
$CI =& get_instance();
$class = $CI->router->fetch_class();
$exclude = array('Home');
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());}
}
}
For Codigniter 4
You can redirect your every request from HTTP to HTTPS in Codeigniter 4 Only one change in App.php in directory config:
/*|--------------------------------------------------------------------------| URI PROTOCOL|--------------------------------------------------------------------------|| If true, this will force every request made to this application to be| made via a secure connection (HTTPS). If the incoming request is not| secure, the user will be redirected to a secure version of the page| and the HTTP Strict Transport Security header will be set.*/public $forceGlobalSecureRequests = false;
change false into true
public $forceGlobalSecureRequests = true;