Create a Router for our Project

Redirect HTTP calls to “index.php” with the help of the “.htaccess” file.

We won’t be creating something sophisticated here, just a basic routing system for our application.

In a nutshell, we’ll:

  • Redirect all the HTTP requests to index.php (the router).
  • Create a routing system with switch.

Redirect all the HTTP requests to the router

We have an index.php file at the root of our application. We’ll use it as our router.

Let’s create a .htaccess file in the root of the project and redirect all the traffic to index.php:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php 

In our .htaccess file, we’ll first activate the runtime rewriting engine of the Apache server, then limit access to physical files with the Apache RewriteCond directive, and redirect all the upcoming requests to the index.php file.

Note: .htaccess is a configuration file for the Apache server. It has no extension but starts with a . (dot) for a hidden file.

In the event that our application or site is not at the root of our server (or if we don’t have a virtual host), we’ll need to create our .htaccess as follows:

RewriteEngine On
RewriteBase /folder/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /folder/index.php [L]

Note: Replace “folder” with the name of the folder that contains our site.

Create a routing switch

Our routing system will work as follows:

  • We’ll get the user requested path with the $_SERVER super global variable.
  • We’ll require the corresponding page.

Let’s see the code in action:

require_once "utils/common.php";

$request = $_SERVER['REQUEST_URI'];

switch ($request) {

    case '':
    case '/':
        require __DIR__ . '/views/index.php';

    case '/projects/list':
        require __DIR__ . '/controllers/project_list.php';

    case '/tasks/list':
        require __DIR__ . '/controllers/task_list.php';

    case '/projects/add':
        require __DIR__ . '/controllers/project.php';

    case '/tasks/add':
        require __DIR__ . '/controllers/task.php';

    case '/reports':
        require __DIR__ . '/controllers/reports.php';

    case (preg_match('/\/projects\/add\?id=\d/', $request) ? true : false):
        require __DIR__ . '/controllers/project.php';

        require __DIR__ . '/views/404.php';

In case the user requires a path that does not exist, we’ll display a custom “Not Found” page. Notice how we make use of regex for a path like /projects/add?id=4.

Live demo

Let’s run the code, so that we can see how it works:

Get hands-on with 1000+ tech skills courses.