How can I avoid direct access to codeigniter controllers, rather than routes?

When we are defining all your URLs through the routes.php file, the direct access to your code-igniter class will make accessible duplicated pages for the website. Duplicated pages affect SEO in large extents, so better to avoid direct access to the controller functions.


Step 1: Create a controller function for 404 response page


Create a separate controller and a normal public function in the controller folder. The following code inside the function makes the 404 error response page.


PHP

/**
* Error Controller
*/
class Errors extends CI_Controller {

    /**
     * Page function to provide 404 response.
     */
    public function show_404() {
       
        # Setting response header as 404
        $this->output->set_status_header('404');
       
        # Load the error view page form views folder (applications/views/error_page_404.php).
        $this->load->view('error_page_404');
    }

}

Step 2: Modify your routes.php file


At this point, you already have a good idea about the config/routes.php file although the routes.php will be similar to the below code after modification:


PHP

$route['404_override'] = 'errors/show_404';

/**
* Your all routes path here....
* ------------------------------
* ------------------------------
* ------------------------------
*/

/**
* Avoid direct access to the controller with the full controller name.
*/
$route['(:any)'] = 'errors/show_404';


There are mainly two points in your routes files:


Overwrite your default 404 error page with defined controller page:  $route['404_override'] = 'errors/show_404';


After defining all your routes, avoid further URL access by pointing all other URLs to the 404 controller page written before:  $route['(:any)'] = 'errors/show_404';


So, pointing all requests to the 404 page after parsing all valid routes will help you to avoid direct access to the controller with controller name and its method names.