1
votes

How do I make

domain.com/api/somecontroller/someaction

and

domain.com/somecontroller/someaction

point to the same controller action:

class somecontroller {

   function someaction() {

   }
}

Note: I don't want to re-route just one action. But I want to reroute all routes of domain.com/api/* to their corresponding URLs without the 'api' prefix.

e.g:

domain.com/api/controller              ->  domain.com/controller
domain.com/api/controller/action       ->  domain.com/controller/action
domain.com/api/controller/action/param ->  domain.com/controller/action/param
domain.com/api/controller/action?key=val ->  domain.com/controller/action?key=val

I tried adding the following in routes.php:

Router::connect('/api', array('controller'=>'index', 'action'=>'index'));
Router::connect('/api/:controller', array('action'=>'index'));
Router::connect('/api/:controller/:action');
Router::connect('/api/:controller/:action.:ext');

It works fine for the rules defined. But I doesn't seem to cover all scenarios. Like it fails when you use URL params, or plugins and other advanced URLs.

Is there an easier way of accomplishing the task that I want?

1
"Is there an easier way of accomplishing the task that I want?" Yeah, it's called mod rewrite. - Rob
You don't need mod_rewrite, cakes routing system takes care of everything. You can use a wildcard and a placeholder, see my answer below. - Happy
Whether you need it or not, mod rewrite is still a better and more efficient way of handling this situation. Just sayin... - Rob

1 Answers

0
votes

You do not need those 4 rules you have as you can use wildcards (*) in CakePHP's routing system.

So in app/Config/routes.php add only one rule which will cover everything you want ..

Router::connect('/api/:action/*', array('controller' => 'mycontroller'));

Then, every request that is like http://domain.com/api/someaction, will end up at http://domain.com/mycontroller/someaction.

The only thing you need to change in my code example is the name of the controller, I have mycontroller specified above.

the :action part you see is basically a placeholder for any actions specified in the request and the * is a wildcard.