How do you redirect to the "base URL" if a web page is not found in CodeIgniter 4?

Viewed 212

How do you redirect to base_url() if a page is not found that matches the current URI?

I have tried this in app/Config/Routes.php, but it's not working:

$routes->set404Override(function () {
    return redirect()->to(base_url());
});
1 Answers

404 Override

When a page is not found that matches the current URI, the system will show a generic 404 view. You can change what happens by specifying an action to happen with the set404Override() option. The value can be either a valid class/method pair, just like you would show in any route, or a Closure:

// Would execute the show404 method of the App\Errors class
$routes->set404Override('App\Errors::show404');

// Will display a custom view
$routes->set404Override(function ()
{
    echo view('my_errors/not_found.html');
});

Solution:

So in your case, you could do:

$routes->set404Override('App\Controllers\Home::index'); ✅
Related