Simple PHP Page Router

This is a simple yet basic PHP routing application created to direct all request to index.php and route the files to it’s relevant paths.

  1. Create the Configuration file

In the root directory, Specify the configuration by creating a .htaccess file to redirect all requests to index.php.


RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+)$ index.php [QSA,L]
  1. Create the Router

Specify the pages you want to redirect by adding the url in the switch statement. It will redirect to your specified file and if the url is not available then it’ll redirect to the default case.


<?php $redirect = $_SERVER['REQUEST_URI']; // You can also use $_SERVER['REDIRECT_URL']; switch ($redirect) { case '/' : case '' : require __DIR__ . '/pages/home.php'; break; case '/contact' : require __DIR__ . '/pages/contact.php'; break; default: require __DIR__ . '/pages/404.php'; break; }
Code language: HTML, XML (xml)
  1. Create the Pages

Create the following home.phpcontact.php404.php files under pages directory and copy the below codes to each files.


Code language: HTML, XML (xml)


Code language: HTML, XML (xml)


<h1>Error! Page Not Found.</h1>
Code language: HTML, XML (xml)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Leave a Reply

Your email address will not be published.