SEO friendly urls in CakePHP using routes

CAKE PHP

Posted on 2016-08-25 01:02:14


Seo friendly urls in CakePHP

First of all, what we want to achieve, we need to change urls looking like that: ‘www.examplesite.com/controller/action/id’ to ‘www.examplesite.com/postTitle-id’ (it would be seo friendly urls) . Why? It’s obivous, search engines likes it, and user likes shorter url, easy to remember. I will show you, how to make our urls seo friendly in a few simple steps.

 

Add following code into you routes.php

 

Router::connect('/:slug-:id',

  array('controller' => 'posts', 'action' => 'view'),

  array(

    'pass' => array('slug' , 'id'),

    'id' => '[0-9]+'

  )

);

According this, every url ‘/posts/view’ will be rewrite to /:slug-:id. Our first array refers to PostsController view() method. The second array passes two parameters ‘slug’ and ‘id’, the line below sets up rules for id values’.

 

Modify your view() method in your PostsController.php

 

function view($id = null, $slug = null) {

  $this->Post->id = $this->params['id'];

  $this->set('post', $this->Post->read());

}

Make sure you have $slug parameter in your view().

 

Replace code in your index.ctp with it:

 

echo $this->Html->link($post['Post']['title'], array(

'controller' => 'posts',

'action' => 'view',

'slug' => Inflector::slug($post['Post']['title'],'-'),

'id'=>$post['Post']['id'])

In 4th line we’re using slug to put the title post, which we use in the first step during routing. seo friendly urls

Source: boryszielonka.pl