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.

Step 2: Modify your routes.php file

At this point, you already have a good idea about the config/routes.php file, otherwise please have a look at: Documentation for Codeigniter Routes. The routes.php will be similar to the below code after modification:

There are mainly two points in your routes files:

  1. Overwrite your default 404 error page with defined controller page:  $route['404_override'] = 'errors/show_404';
  2. 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.