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?

Advertisements

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. 5 Comments.

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

  2. Clemens Tolboom

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

  1. Pingback: setfive.com: 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

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: