Search code examples
phpcodeigniter-4

Codeigniter 4 default routing with dynamic arguments for SEO url's


I am working on a CMS in Codeigniter 4 and i'm running into some routing issues i can't figure out.

I want to use SEO url's for the front-end so i need to redirect all traffic to one method with zero or more parameters. Except for calls that could be directed to an existing controller. Without having to setup all possible routes in my system.

For example

website.local/survival/weeks > Should redirect to the default controller method passing 2 arguments

website.local/ > Should also redirect to the default controller method passing no arguments

But

website.local/admin/pages/page/1 > Should direct to the existing method

I have already created the default method

<?php namespace App\Controllers;

class Pages extends BaseController
{
    public function index()
    {
        $args = func_get_args();
        dd($args);
    }

And in config/Routes.php i've tried this

// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/', 'Pages::index');

Which would work, except when i pass arguments it redirects to 404

Also i tried this

$routes->get('(:any)', 'Pages::index/$1');

But now everything that i did not define in a route will also be directed to my default method

Then i tried overriding the 404 page to my default method like this:

$routes->set404Override('App\Controllers\Pages::index');

But it seems i'm unable to pass arguments this way.

Does anyone know how to do this without changing system files or having to set a route for every single method in my system?


Solution

  • In Routes.php set the 404 override to the method that should catch all:

    $routes->set404Override('App\Controllers\Pages::index');
    

    Then in the method retrieve the URI segments like this:

    <?php namespace App\Controllers;
    
    class Pages extends BaseController
    {
        public function index()
        {
            $args = $this->request->uri->getSegments();
            dd($args);
        }
    
    }
    

    Now you can show the 404 from there if a page is not found.