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]

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:

// 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?

About Gonzalo Ayuso

Web Architect. PHP, Python, Node, Angular, ionic, PostgreSQL, Linux, ... Always learning.

Posted on October 15, 2012, in php and tagged , , , . Bookmark the permalink. 6 Comments.

  1. Really like this as an alternative to .htaccess!

  2. Clemens Tolboom


    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’;

  3. Multit Techno Systems

    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.

  1. Pingback: Why you should build a static site with Silex « {5} Setfive - Talking to the World

  2. Pingback: URL rewriting in built-in web server of PHP | Blog of Leonid Mamchenkov

Leave a Reply to Multit Techno Systems Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: