CakePHP redirect routing

2019-08-07 15:16发布

In my CakePHP 2.3 application, I want example.com/come/Harry to redirect example.com/myworks/people/Harry.

This works, but this connects.

Router::connect ('/come/:myname',
    array('controller' => 'myworks', 'action' => 'people'),
    array(
        'pass' => array('myname')
    )
);

I need a 301 redirection. I tried this:

Router::redirect ('/come/:myname',
    array('controller' => 'myworks', 'action' => 'people'),
    array(
        'pass' => array('myname')
    )
);

But it redirected to example.com/myworks/people/. How can I pass argument to my action while redirecting ?

3条回答
smile是对你的礼貌
2楼-- · 2019-08-07 15:27

Per the documentation you want to use persist rather than pass for redirects. This code should work as you want:

Router::redirect ('/come/*',
    array('controller' => 'myworks', 'action' => 'people',
          '?' => array('processed' => 1)),
    array(
        'persist' => array('myname')
    )
);

The reason is because you're generating a new url when you redirect:

  • pass is used to define which of the routed parameters should be shifted into the pass array. Adding a parameter to pass will remove it from the regular route array. Ex. 'pass' => array('slug')
  • persist is used to define which route parameters should be automatically included when generating new urls. You can override persistent parameters by redefining them in a url or remove them by setting the parameter to false. Ex. 'persist' => array('lang')
查看更多
爷、活的狠高调
3楼-- · 2019-08-07 15:28

Use following code

Router::redirect ('/come/*',
    array('controller' => 'myworks', 'action' => 'people'),
    array('params' => '[a-zA-Z0-9]+')
);
查看更多
做个烂人
4楼-- · 2019-08-07 15:37

You are pretty much there, but you need to define your named params so that cake knows that the url is valid.

Reference, http://book.cakephp.org/2.0/en/development/routing.html#passing-parameters-to-action

Router::redirect (
    '/come/:myname',
    array('controller' => 'myworks', 'action' => 'people'),
    array(
        'myname' => '[a-z]+',
        'pass' => array('myname'),
        'status' => '301'
    ),
);
查看更多
登录 后发表回答