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.
- Create the Configuration file
In the root directory, Specify the configuration by creating a .htaccess file to redirect all requests to index.php.
.htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]
- 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.
index.php
<?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;
}
- Create the Pages
Create the following home.php, contact.php, 404.php files under pages directory and copy the below codes to each files.
pages/home.php
<h1>Home</h1>
pages/contact.php
<h1>Contact</h1>
pages/404.php
<h1>Error! Page Not Found.</h1>
Hope this tutorial helped you! Feel free to drop your opinion at the comment section.