How to hide controller name in CodeIgniter url?

In CodeIgniter, you can hide the controller name in the URL by setting up a default controller in the "routes.php" configuration file, located in the "application/config" directory. Here's how you can do it:

  1. Open the "routes.php" file and set the default controller by adding the following code:

$route['default_controller'] = 'YourDefaultController';

Replace "YourDefaultController" with the name of the controller you want to be the default one.

  1. In your default controller, define a method that will handle all requests that do not match a specific URL pattern. For example:
class YourDefaultController extends CI_Controller {

  public function index()
  {
    // your code here
  }

  public function _remap($method)
  {
    if (method_exists($this, $method))
    {
      $this->$method();
    }
    else
    {
      // redirect to a 404 error page
    }
  }

}

This method, called "_remap", will allow you to handle all requests that don't match a specific URL pattern, such as the one defined by a specific method in the controller.

  1. Save the changes and test your application. The controller name should now be hidden in the URL.

For example, if you previously had a URL like this:

http://example.com/YourController/method

It should now be like this:

http://example.com/method

Keep in mind that you'll need to update your links and URLs throughout your application to match the new URL structure.

Enjoyed this article? Stay informed by joining our newsletter!

Comments

You must be logged in to post a comment.

About Author
Recent Articles