繁体   English   中英

带参数的 CakePHP 路由重定向

[英]CakePHP route redirect with parameters

我需要保持 SEO 链接处于活动状态,因此我正在尝试 301 将 google 流量重定向到新的 CakePHP 路由。

我去:

http://localhost/jakne/someCategory/item-slug

我希望它 301 重定向到:

http://localhost/product/item-slug

所以我尝试了route::redirect但我无法让它工作。 这方面的文档也不存在:(

$routes->redirect(
    '/jakne/:subcategory/:item',
    ['controller' => 'Catalog', 'action' => 'product'],
    ['status' => 301, 'pass' => ['item']]
);

我的Catalog::product看起来像:

public function product($productId) {
}

我总是收到没有参数传递给操作的错误。 我错过了什么? :(

在重定向路由中保留参数的选项不是pass (用于常规路由并定义要作为函数参数传递的参数),它是persist ,即您的路由需要类似于:

$routes->redirect(
    '/jakne/:subcategory/:item',
    ['controller' => 'Catalog', 'action' => 'product'],
    ['status' => 301, 'persist' => ['item']]
);

这应该可以正常工作,假设您连接了一个正确的目标路由,该路由具有一个名为item的参数,例如。

$routes->connect(
    '/product/:item',
    ['controller' => 'Catalog', 'action' => 'product'],
    ['pass' => ['item']]
);

通常,您可能需要考虑在服务器级别进行此类重定向(例如通过 Apache 上的mod_rewrite ),这在性能方面要好得多。

附言。 浏览器会缓存301重定向,因此在更改此类重定向时,请确保事后清除缓存。

也可以看看

所以事实证明这很简单。 我使用它来根据管理员在控制面板中输入的内容动态生成重定向列表。 当 URL 更改并且尚未被 google bot 重新扫描时,我们使用它来保持 google 流量。

$builder->redirect('/from-url', '/to-url', ['status' => 301]);

试试这种对我有用的方法:示例请求,例如: localhost:08080/get-username?id=%3Cid%3E

路线:

$routes->connect('/get-username', ['controller' => 'Users', 'action' => 'getUserName']);

控制器 :

    class UsersController extends AppController {
       public function initialize() {
          parent::initialize();
           $this->loadComponent('RequestHandler');
       }

       public function beforeFilter(Event $event) {
          parent::beforeFilter($event);
          $this->set('_serialize', false);
          $this->Auth->allow([
            'getUserName'
          ]);
       }

       public function getUserName() {
        $id = $this->request->getQuery('id');

       }
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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