问题
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 ?
回答1:
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')
回答2:
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'
),
);
回答3:
Use following code
Router::redirect ('/come/*',
array('controller' => 'myworks', 'action' => 'people'),
array('params' => '[a-zA-Z0-9]+')
);
来源:https://stackoverflow.com/questions/17976154/cakephp-redirect-routing