Search code examples
cakephp-3.4

Routing with regex in CakePHP#


I'm looking for help on setting up routes in CakePHP3.4.6 where urls are variable. For instance, I want the following urls:

/California/Posts/view/Skateboard/Jan2nd/10
/Texas/Posts/view/Truck/Feb10th/35

to connect to

/Posts/view/10
/Posts/view/35

respectively. When doing so, I need the URLs preserved in the browser. (i.e. browser URL shows /California/Posts/view/Skateboard/Jan2nd/10 while content is served for /Posts/view/10)

Can this be done through configuring routes.php? Any advice will be most appreciated.

I tried using rewrite rules in webroot/.htaccess such as:

RewriteRule ^[^/]+/Posts/view/[^/]+/[^/]+/(\d+)$ /Posts/view/$1 [L]

But this just ends up in 404 errors. The pattern match seems to be correct as the following rule works:

RewriteRule ^[^/]+/Posts/view/[^/]+/[^/]+/(\d+)$ http://www.google.com [L]

Thanks,


Solution

  • Managed to figure this out.

    $routes->connect('/:state/Posts/view/:title/:date/:id',
                     ['controller' => 'Posts', 'action' => 'view'],
                     ['id' => '\d+', 'pass' => ['id']]
    

    Did the job