CakePHP

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'
    )));

How to Add a Trailing Slash to URLs in CakePHP

I’m building more web projects but found out that Content management System (CMS) that I normally use like WordPress, phpMyDirectory and others does not fulfill my needs. I’ve learned about PHP Framework such as CakePHP & decide to try it. With PHP Framework, I can build my own CMS. After many hours of working with it, I get it to works as per my needs.

My first CakePHP project completed but find out that many of the URLs generated does not have trailing slash. There is speculation that it is important for SEO. To do this you have to modify 2 files.

1. /app/View/Helper/AppHelper.php

Add the following codes in AppHelper.php. You can add more extension if you use it in order to avoid trailing slash inserted after the extension.

class AppHelper extends Helper {

function url($url = null, $full = false) {
        $routerUrl = Router::url($url, $full);
        if (!preg_match('/\\.(rss|html|js|css|jpeg|jpg|gif|png|xml?)$/', strtolower($routerUrl)) && substr($routerUrl, -1) != '/') {
            $routerUrl .= '/';
        }
        return $routerUrl;
    }

}

2. /app/webroot/.htaccess

Need to modify .htaccess file so that non trailing slashed URLs will be redirected to trailing slashed URLs. This is to avoid duplicate content, which is not good for SEO. This code is not limited to CakePHP, you can you for any other purpose.

<IfModule mod_rewrite.c>
 # Add trailing slash
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
 RewriteRule ^(.*)$ http://www.yourwebsite.com/$1/ [L,R=301]
</IfModule>