简体   繁体   中英

Remove controller Index from URL - Zend Framework 1.12 and Routes

In my project I have some pages defined in my index controller, like ie. the About us page. In order for me not to have to type domain.com/index/about but domain.com/about I have this route:

$route = new Zend_Controller_Router_Route_Static ( 'about', array (
        'controller' => 'Index',
        'action' => 'about'
) );

$router->addRoute ( 'about', $route );

It does the job. The problem is that sometimes I have 6 or 7 pages and I have to repeat this route 6 or 7 times. Is there a way for me to do a route that would always remove " index " from the url? I would never need a url that has index in it. Thanks!

You can write dynamic routes by avoiding the static route type:

    $route = new Zend_Controller_Router_Route(
        '/:action', 
        array (
            'controller' => 'index',
            'action' => 'index',
        )
    );
    $router->addRoute('pages', $route);

This will add a route called 'pages' that will match any single action in the index controller. The action and controller defined in this route are merely the defaults and as you are not passing the controller as a variable it will always route to the IndexController. The action will default to indexAction but can be overridden by the route, ie:

/about -> IndexController / aboutAction
/contact -> IndexController / contactAction
etc ...

Bear in mind this will override any other routes so you need to structure your routing heirachy properly. Routes defined later in the process will override routes already defined.

For more information check the docs: Zend Framework Standard Router

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM