SEO friendly urls in CakePHP using routes

Seo friendly urls in CakePHP


First of all, what we want to achieve, we need to change urls looking like that: ‘’ to ‘’ (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

  array('controller' => 'posts', 'action' => 'view'),
    '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'],'-'),

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

Dodaj komentarz