How to rewrite urls with PHP 5.4’s built-in web server


PHP 5.4 comes with a flaming built-in web server. This server is (obviously) not suitable to use in production environments, but it’s great if we want to check one project quickly:

  • git clone from github
  • composer install to install dependencies
  • run the built-in web server and test the application.
php -S localhost:8888 -t www/

But is very usual to use mod_rewrite or similar to send all requests to the front controller. With apache is pretty straight forward to do it:

<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

But, does it work with the built-in web server? The answer is yes, but with another syntax. We only need to create one router file and start our server with this router:

<?php
// www/routing.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;
} else {
    include __DIR__ . '/index.php';
}

And now we start the server with:

php -S localhost:8888 www/routing.php

Easy, isn’t it?

6 thoughts on “How to rewrite urls with PHP 5.4’s built-in web server

  1. ~Thanks

    We rewrote this as it misses .js then did

    $request_uri = __DIR__ . $_SERVER[“REQUEST_URI”];
    if (file_exists($request_uri)) {
    return false;
    } else {
    include __DIR__ . ‘/index.php’;
    }

  2. I have the same thoughts on much of this material. I am glad I’m not the only person who thinks this way. You have really written an excellent quality article here. Thank you very much.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.