How to enable seo-friendly urls in cakephp?

Member

by dudley , in category: SEO , 7 months ago

How to enable seo-friendly urls in cakephp?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by percy_bauch , 7 months ago

@dudley 

To enable SEO-friendly URLs in CakePHP, you need to follow these steps:

  1. Enable mod_rewrite module: Ensure that the mod_rewrite module is enabled on your server. If it is not enabled, you can enable it in your server's configuration or .htaccess file.
  2. Configure your .htaccess file: CakePHP comes with a default .htaccess file in the webroot directory. If it is not already present, you can create one. Open the .htaccess file and make sure the following lines are present:
1
2
3
4
5
6
7
8
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>


The above code snippet ensures that all requests to non-existing directories or files are redirected to the index.php file.

  1. Configure the routing: In your routes.php file in the config directory, you can define custom routing rules that map SEO-friendly URLs to controller actions. For example, to map the URL /products/123 to the view action of the ProductsController with 123 as the parameter, you can add the following code:
1
$routes->connect('/products/:id', ['controller' => 'Products', 'action' => 'view'], ['pass' => ['id']]);


This will enable URLs like /products/123 instead of the default CakePHP URL structure.

  1. Update link generation: In your views or templates, use the CakePHP HTML helper's link method to generate URLs. For example, instead of using hardcoded URLs like /products/123, you can use the following code:
1
echo $this->Html->link('View Product', ['controller' => 'Products', 'action' => 'view', $product['id']]);


This will generate the appropriate SEO-friendly URL based on your routing configuration.


With these steps, you should be able to enable SEO-friendly URLs in your CakePHP application.