Redirect in CodeIgniter 4

Download the latest version of CodeIgniter 4 and unzip source code to new folder named LearnCodeIgniter4WithRealApps

Cut index.php and htaccess files in public folder to root folder of project

Open index.php in root folder find to line 16 replace path to Paths.php file as below:

$pathsPath = realpath(FCPATH . '/app/Config/Paths.php');

Open App.php in app/Config folder find to line 39 remove index.php string in $indexPage variable as below:

public $indexPage = '';

Open App.php file in app/Config folder. Set value for $baseURL variable as below:

public $baseURL = 'http://localhost:8091/LearnCodeIgniter4WithRealApps/';

Create new PHP file named Demo.php in app/Controllers folder as below:

<?php

namespace App\Controllers;

class Demo extends BaseController
{

	public function __construct()
	{
		helper(['url']);
	}

	public function index()
	{
		return view('demo/index');
	}

	public function clickMe()
	{
		return $this->response->redirect(site_url('demo/index2'));
	}

	public function index2()
	{
		return view('demo/index2');
	}
}								

Create new folder named demo in app/Views folder. In this folder, create new PHP file named as below:

Index View

In demo folder, create new PHP file named index.php as below:

<html>

	<head>
		<title>Redirect in Codeigniter 4</title>
	</head>

	<body>

		<h3>Index</h3>
		<a href="<?= site_url('demo/clickMe') ?>">Click Me</a>
		
	</body>

</html>

Index2 View

In demo folder, create new PHP file named index2.php as below:

<html>

	<head>
		<title>Redirect in Codeigniter 4</title>
	</head>

	<body>

		<h3>Index 2</h3>
		<a href="<?= site_url('demo/index') ?>">Back</a>

	</body>

</html>
			

Open Routes.php file in app/Config folder and define routes as below:

$routes->get('/', 'Demo::index');
$routes->get('/demo/index2', 'Demo::index2');
$routes->get('/demo/clickMe', 'Demo::clickMe');

Access index action in Demo controller with following url: http://localhost:8091/LearnCodeIgniter4WithRealApps/demo/index

Output