skip to Main Content

I need to keep SEO links active so I’m trying to 301 redirect google trafic to new CakePHP route.

I go to:

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

And I want it to 301 redirect to:

http://localhost/product/item-slug

So I tried with route::redirect but I can’t make it work. Doc on this is also non existent 🙁

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

My Catalog::product looks like:

public function product($productId) {
}

I always get error that no parameter was passed to the action.
What am I missing? 🙁

3

Answers


  1. Chosen as BEST ANSWER

    So it turns out this is quite simple. I use this to dynamically generate a list of redirects based on what admins enter in the control panel. We use this to keep google traffic when the URL changes and is not rescanned by the google bot yet.

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

  2. The option for retaining parameters in redirect routes isn’t pass (that’s for regular routes and defines which parameters to pass as function arguments), it’s persist, ie your route would need to be something like:

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

    This should work fine, assuming you have a proper target route connected that has a parameter named item, something like.

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

    Generally you may want to consider doing such redirects on server level instead (for example via mod_rewrite on Apache), performance wise that’s much better.

    ps. Browsers do cache 301 redirects, so when making changes to such redirects, make sure that you clear the cache afterwards.

    See also

    Login or Signup to reply.
  3. Try this ways it is working for me:
    Example request like: localhost:08080/get-username?id=%3Cid%3E

    Routes :

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

    Controller :

        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');
    
           }
       }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search