我需要像这样重定向(301)网址:
https://website.com/products/view/id
为:
https://website.com/products/product-name-slug
我知道如何使slug版本的url工作,但我不想完全禁用旧版本,而是希望它们301重定向到它的slug版本。 我不希望它们同时工作,因为它被Google SEO视为重复内容。
我也不想为routes.php中的每个产品编写重定向,如下所示:
Router::redirect( '/product/view/1001', [ 'controller' => 'products', 'action' => 'view', 'product-1001-name-slug' ] );
相反,我宁愿拥有动态查找功能来为我做这件事。
我怎么能在CakePHP 2.x中做到这一点?
答案 0 :(得分:1)
答案 1 :(得分:0)
这是@ burzum的回答示例:
在routes.php中:
Router::connect(
'/product/view/:slug',
array( 'controller' => 'base_products', 'action' => 'view' ),
array( 'pass' => array( 'slug' ) )
);
Router::connect(
'/base_products/view/:id',
[ 'controller' => 'product', 'action' => 'view', 'model' => 'BaseProduct' ],
[ 'routeClass' => 'IdToSlugRoute' ]
);
在app / Routing / Route / IdToSlugRoute.php中:
public function parse($url) {
$params = parent::parse($url);
if (!$params) {
return false;
}
if (!$this->response) {
$this->response = new CakeResponse();
}
App::import('Model', $params['model']);
$Model = new $params['model']();
$instance = $Model->find('first', array(
'conditions' => array($params['model'] . '.id' => $params['id']),
'recursive' => 0
));
$slug = getSlug( $instance[$params['model']]['id'], $instance[$params['model']]['name'] );
$redirect = ['controller' => $params['controller'], 'action' => $params['action'], $slug];
$status = 301;
$this->response->header(array('Location' => Router::url($redirect, true)));
$this->response->statusCode($status);
$this->response->send();
$this->_stop();
}
app / Controller / BaseProductsController.php中的:
function view($slug)
{
$id = getIdFromSlug($slug);
$product = $this->BaseProduct->find('first', array(
'conditions' => array('BaseProduct.id' => $id),
'recursive' => 2
));
...
}
额外:
function getIdFromSlug( $slug ) {
$pieces = explode( "-", $slug );
return $pieces[0];
}
function getSlug( $id, $name ) {
return $id . '-' . Inflector::slug($name, '-');
}