Search code examples
phpcodeignitercodeigniter-2

How to remove all controller names from url in codeigniter


I have multiple controllers in a Codeigniter project. I need to hide these controller names. For eg: I have two controller, home and school. Each school have their own page which includes about,gallery,contact etc. and url should be http://www.sitename.com/schoolname. I hide home controller using routes.php. $route['(:any)'] = 'home/$1'; But it shows error in school controller. Please help me..... Thanks.


Solution

  • It is not true that a controller name is absolutely required.

    In routes.php first define default controller to be home (when user accesses homepage sitename.com)

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

    Then you create the rule that any other page should be redirected to school controller:

    $route['.*'] = 'school';
    

    Now the home.php controller will look like this:

    class Home extends CI_Controller {
    
        public function Index()
        {
            echo "This is the homepage";
        }
    
    }
    

    And in the school.php controller you have to manually get the name of the school from requested URL:

    class School extends CI_Controller {
    
        public function _remap()
        {
            echo "User requested school: " . $this->uri->segment(1);
        }
    
    }
    

    Why use _remap method? Because it will be called everytime regardless of what's in URL or routing.

    From the docs:

    If your controller contains a method named _remap(), it will always get called regardless of what your URI contains.