The Simplest PHP Router

I wanted to create the absolute most basic routing code in PHP, so here it is. We will direct ALL traffic to index.php and route to the new files from there.

Redirect all requests to index.php

In the root of your project, create a .htaccess file that will redirect all requests to index.php.

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

Create a routing switch

Get the requested path with $_SERVER['REDIRECT_URL'], and require the page you want to display. I have '' and '/' for both and


$request = $_SERVER['REDIRECT_URL'];

switch ($request) {
    case '/' :
        require __DIR__ . '/views/index.php';
    case '' :
        require __DIR__ . '/views/index.php';
    case '/about' :
        require __DIR__ . '/views/about.php';
        require __DIR__ . '/views/404.php';

Create the views

Create a /views directory and place the files.


That's it!

Join the newsletter

I write about JavaScript, programming, and front-end design. Join 6000+ other developers in keeping up with my content. Unsubscribe whenever. Never any spam, ads, or affiliate links.