Skip to main content
How to Create a Custom CodeIgniter 404 Page (Complete Guide)

How to Create a Custom CodeIgniter 404 Page (Complete Guide)

Guide content

The 404 Not Found error page is one of the most critical components of any web application built with the CodeIgniter framework. When a visitor attempts to access a missing URL or a broken link, they should be greeted with a thoughtfully designed, helpful custom 404 page rather than a generic server error or an unstyled blank screen.

In this step-by-step guide, we will explore how to create and configure a custom CodeIgniter 404 page for both major framework versions: CodeIgniter 3 (CI3) and CodeIgniter 4 (CI4). We will cover routing configurations, custom controllers, handling AJAX and REST API JSON responses, proper HTTP status headers, and best practices to safeguard your website search engine optimization (SEO) and user experience.

Why Customizing the 404 Page Matters for Your Site

A customized 404 error page delivers essential technical, usability, and marketing benefits that every modern web application requires:

  • Enhanced User Experience (UX): A custom page provides search bars, navigation links, and a clear call-to-action to return home, preventing visitors from abandoning your site immediately.
  • SEO Protection & Soft 404 Prevention: Properly signaling an HTTP 404 Not Found header prevents search engines like Google from indexing missing pages as duplicate content (Soft 404 errors).
  • Brand Consistency: Maintaining your website header, footer, color palette, and typography keeps the user experience seamless and professional across all pages.
  • Error Tracking & Diagnostics: You can integrate logging mechanisms within your custom 404 controller to catch broken links and fix them proactively before losing traffic.

Step 1: Customizing the 404 Page in CodeIgniter 3

In CodeIgniter 3, there are two primary methods to customize the 404 error response: modifying the default HTML template or setting up a full 404_override controller.

Method 1: Editing the Default View Template in CI3

CodeIgniter 3 ships with a default 404 error template located at:

application/views/errors/html/error_404.php

You can edit this file directly to add your HTML and CSS styling. While quick, this approach does not allow you to load CodeIgniter models, helpers, or external libraries dynamically.

Method 2: Using 404_override with a Custom Controller in CI3 (Recommended)

To gain full access to CodeIgniter functions, controllers, and database models inside your 404 page, use the 404_override routing parameter. Follow these steps:

  • Configure Routes (routes.php): Open application/config/routes.php and set:
    $route['404_override'] = 'mycustom404';
  • Create the Custom Controller (Mycustom404.php): Create a controller file at application/controllers/Mycustom404.php:
    <?php
    class Mycustom404 extends CI_Controller {
        public function __construct() {
            parent::__construct();
        }
        public function index() {
            $this->output->set_status_header('404');
            $data['title'] = 'Page Not Found - 404';
            log_message('error', '404 Page Not Found: ' . current_url());
            $this->load->view('custom_404_view', $data);
        }
    }
  • Create the View File (custom_404_view.php): Create application/views/custom_404_view.php containing your styled markup and navigation options.

Step 2: Customizing the 404 Page in CodeIgniter 4

In CodeIgniter 4, the framework utilizes an updated architecture with robust exception handling via namespaces and response objects.

Method 1: Customizing the Error View Template in CI4

In production mode, CI4 loads the default 404 error template located at:

app/Views/errors/html/error_404.php

Updating this file customizes the output when a PageNotFoundException is thrown in production environment.

Method 2: Configuring 404 Override Controller in CI4

For custom routing and controller logic in CodeIgniter 4, configure app/Config/Routes.php:

  • Set the Override Handler: In app/Config/Routes.php, add:
    $routes->set404Override('App\Controllers\NotFound::index');
  • Create the NotFound Controller: Create app/Controllers/NotFound.php:
    <?php
    namespace App\Controllers;
    use CodeIgniter\Exceptions\PageNotFoundException;
    class NotFound extends BaseController {
        public function index() {
            response()->setStatusCode(404);
            log_message('warning', 'CI4 404: ' . current_url());
            return view('errors/custom_404');
        }
    }

Handling AJAX Requests and REST API 404 JSON Responses

Modern applications frequently handle asynchronous AJAX calls or expose RESTful API endpoints. When an API route is missing, returning a full HTML web page breaks client-side parsing. Instead, your 404 handler should inspect the incoming request headers and return a structured JSON response.

Handling 404 JSON Responses in CodeIgniter 3

Inside your custom controller Mycustom404.php, check if the request is an AJAX call or matches an API URI pattern:

if ($this->input->is_ajax_request() || strpos($this->uri->uri_string(), 'api/') === 0) {
    $this->output
        ->set_status_header(404)
        ->set_content_type('application/json', 'utf-8')
        ->set_output(json_encode([
            'status' => false,
            'error' => 404,
            'message' => 'Requested API route not found'
        ]));
    return;
}

Handling 404 JSON Responses in CodeIgniter 4

In CodeIgniter 4, utilize content negotiation or inspect the request service inside NotFound.php:

$request = service('request');
if ($request->isAJAX() || $request->header('Accept')?->getValue() === 'application/json') {
    return response()->setStatusCode(404)->setJSON([
        'success' => false,
        'code' => 404,
        'message' => 'Resource not found'
    ]);
}

Ensuring Proper HTTP 404 Status Headers for SEO

A common mistake developers make is returning a custom 404 page with an HTTP 200 OK status code. This signals to search engines that the missing page is valid, leading to indexing issues and Soft 404 warnings.

Always verify that your controller explicitly emits the 404 status code:

  • In CodeIgniter 3: Use $this->output->set_status_header('404');
  • In CodeIgniter 4: Use response()->setStatusCode(404); or throw throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();

Server Rewrites & Hosting Configuration (Nginx & Apache)

To ensure all missing URL requests route properly through your CodeIgniter application rather than hitting default web server error pages, verify your web server rewrite rules:

  • Apache .htaccess Rules: Place an .htaccess file in the web root:
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
  • Nginx Server Block Configuration: Ensure your Nginx configuration forwards requests to index.php:
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

Logging Missing Pages and Automated Redirects

Building a custom 404 handler allows you to log missing URLs directly to your application logs or a database table. By reviewing log files periodically, you can detect broken internal links or outdated external links and set up 301 Permanent Redirects to preserve your search rankings and direct traffic effectively.

How Hosting Quality Impacts 404 Error Handling

During traffic spikes or automated vulnerability scanning, missing page requests can generate hundreds of dynamic PHP requests. Host your CodeIgniter applications on high-performance infrastructure like VavaHost Cloud Hosting Plans to ensure fast PHP execution and optimized server-side caching.

To further optimize web performance and fix common network issues, check out our guide on fixing the ERR_CACHE_MISS error.

Best Practices for Designing an Effective 404 Page

Turn a dead-end 404 error into a helpful navigational hub by implementing these design best practices:

  • Clear Messaging: State plainly that the requested page could not be found or has moved.
  • Prominent Search Input: Provide a search box so visitors can locate content easily.
  • Key Navigation Links: Add links to your homepage, services, blog, and support portal.
  • Clean Visual Design: Use friendly illustrations matching your brand identity.

Key Takeaways

Setting up a custom CodeIgniter 404 page is essential for maintaining strong SEO health, preserving user trust, and delivering a cohesive brand experience. By configuring the 404 override route and ensuring correct HTTP status codes in CodeIgniter 3 or 4, you safeguard your web application against broken links and lost traffic.

Ready to Launch a Faster Website?

Get a free domain, free SSL certificate, and automated backups. Start your risk-free trial today.

View Plans & Pricing

Find Your Plan & Start Free

What type of project are you building?

We'll match you with the perfect plan based on your real needs