How to force ssl in codeigniter?

How to force ssl in codeigniter?

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Forcing SSL in CodeIgniter Without Editing .htaccess

While redirecting HTTP traffic to HTTPS via an .htaccess file is the standard approach for Apache servers, there are scenarios where you cannot modify server-level configuration files. This might happen if you are working within a shared hosting environment with restricted access or managing a specific application container that lacks write permissions to the document root. In these cases, you can enforce SSL from within your CodeIgniter 3 application logic by intercepting requests and issuing HTTP redirects before the framework processes the page.

The Logic Behind Application-Level Redirects

To force SSL without touching .htaccess, you must leverage CodeIgniter's output buffering or a custom filter to detect the protocol and location of the incoming request. The core mechanism relies on checking the $_SERVER['HTTPS'] variable or the scheme in the URI. If the connection is not secure, your application needs to send an HTTP 301 (Permanent Redirect) response back to the client with the URL updated to use https://.

It is crucial to understand that this method operates at the application layer rather than the server layer. Consequently, it incurs a slight performance overhead compared to a reverse proxy or .htaccess rule because your PHP script must execute before the redirect occurs. Additionally, this approach only protects traffic routed through your specific domain; if users access your site via an IP address without a valid hostname, SSL enforcement becomes more complex unless that IP also has a certificate configured.

Implementing the Redirect Hook

The most robust way to handle this in CodeIgniter 3 is by creating a custom filter or hook within the application.php file. This ensures the redirect happens early in the request lifecycle for all controllers and pages. You can define a helper method that checks the protocol and redirects if necessary.

Here is an example of how you might structure a utility function to enforce this behavior globally:

<?php
// application/helpers/security_helper.php

if ( ! function_exists('force_ssl')) {
    /**
     * Force HTTPS redirect if the request is not secure.
     */
    function force_ssl()
    {
        // Check if the request is over HTTP or if HTTPS is explicitly false
        $is_secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';

        // Note: On some Windows servers, $_SERVER['HTTPS'] might be set to '1' 
        // even for non-SSL requests due to IIS configuration. 
        // Always check the URI scheme as a fallback.
        if ($is_secure || parse_url($_SERVER['REQUEST_URI'], PHP_URL_SCHEME) === 'https') {
            return;
        }

        // Set the protocol and host
        $protocol = 'https';
        $host = $_SERVER['HTTP_HOST'];
        
        // Construct the secure URL
        $secure_url = 'http://' . $host . $_SERVER['REQUEST_URI'];
        
        // Replace with HTTPS
        $secure_url = str_replace('http://', 'https://', $secure_url);

        // Issue a 301 redirect
        header('HTTP/1.0 301 Moved Permanently');
        header('Location: ' . $secure_url, true, 301);
        exit();
    }
}

Integrating the Check into Your Application

To make this function execute for every page load in CodeIgniter 3, you need to call it inside your application.php file. This file is loaded automatically by the framework before any controller logic runs.

Locate the application.php file in your root directory and add a check within the __autoload() function or at the very top of the file, provided it does not interfere with other initialization hooks. A common pattern involves checking this condition immediately after loading the configuration:

// application/application.php
use CodeIgniter\CodeIgniter;

class Application extends \CodeIgniter\CodeIgniter {

    public function __construct()
    {
        parent::__construct();
        
        // Force SSL check early in the lifecycle
        if (config('App') !== null) {
            // Only force if you are not on a secure connection and 
            // perhaps excluding specific paths like login pages if needed
            if (! isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
                force_ssl();
            }
        }
    }

    public function index()
    {
        return redirect()->to('/');
    }
}

Critical Considerations and Pitfalls

When implementing application-level SSL enforcement, you must account for browser caching. Since a 301 redirect is cached by browsers, if you ever decide to switch back to HTTP (or disable the rule) in the future, users may remain stuck on the HTTPS version unless they clear their cache or you issue a 302 redirect initially.

Furthermore, this method does not handle subdomains automatically unless you explicitly check $_SERVER['HTTP_HOST'] against your allowed domains. If a user accesses http://www.example.com, it will redirect to https://www.example.com. However, if they access http://mail.example.com and that subdomain doesn't have its own certificate, the browser might show a security warning upon clicking through.

Finally, remember that this solution assumes your server supports HTTP/1.0 or 1.1 redirects correctly. If you are behind a load balancer or reverse proxy, ensure they pass the necessary headers (X-Forwarded-Proto) so that your application logic can accurately determine if the original connection was secure.

Our network