SEO

Redirect Default CakePHP Pagination URL to SEO Friendly URL with .htaccess


In the previous post, I post a guide on how to create SEO friendly URL in CakePHP pagination.

However, if you already use default CakePHP pagination prior to that, you want to redirect the old pagination URL to the new SEO friendly URL.

I’m using .htaccess file to accomplish this.

Let’s take an example, by default we will have pagination URL like this

http://www.website.com/post
http://www.website.com/post/page:2
http://www.website.com/post/page:3
...

we would like to redirect to

http://www.website.com/post
http://www.website.com/post/page/2
http://www.website.com/post/page/3
...

To redirect, we have to edit .htaccess file located at /app/webroot/.htaccess. Next, add the following code.

RewriteEngine On
RewriteBase /
RewriteRule ^(.+)/page:([0-9]+)/$ /$1/page/$2/ [R=301,L]

SEO Friendly URL in CakePHP Pagination


By default, CakePHP Pagination will have “page:X” in the URL where X is the page number (except the first page). Many SEO expert feel that this type of URL is not SEO friendly. From webmaster point of view, this kind of URL doesn’t look nice too.

Let’s take an example, by default we will have pagination URL like this

http://www.website.com/post
http://www.website.com/post/page:2
http://www.website.com/post/page:3
...

we would like to change it to

http://www.website.com/post
http://www.website.com/post/page/2
http://www.website.com/post/page/3
...

We have to modify 3 files to get this done

1. /app/Config/routes.php

Add or modify the existing route to

Router::connect('/post/page/:page', array(
    'controller' => 'post',
    'action' => 'index'
), array(
    'pass' => array(
        'page'
    ),
    'page' => '[\d]+'
));

2. /app/Controller/PostsController.php

Add or modify the existing controller to

public function index($page = 1) {
    // ...
    $this->request->params['named']['page'] = $page;
    // ...
}

3. /app/View/Posts/index.ctp

Add or modify the existing view to

$paginator->options(array(
    'url'=> array(
        'controller' => 'post',
        'action' => 'index'
    )));

Page 1 of 512345