Add url rewriting router to PHP built-in server

While developing a project, PHP built-in server is much more flexible and easy to use compared to desktop setups like LAMP, XAMP, WAMP, etc.

However, without Apache, you also lose access to the magical and powerful .htaccess feature where you can create simple rewrite rules.

What if our application needs such rewrites like loading .html files for permalinks without extension?

Don’t worry. PHP provides an excellent and simple solution for this as well. You can create your router.php and call it while starting the server. Now, you are free to add any rewrite rule or any other condition to run your code.

To do this, create a file named router.php in your project root. You can choose any name for this file, but router.php provides the right context.

In this use case, I have a static website with all the static content like HTML, CSS, etc. But my permalinks are without HTML extension, though the file name is the same. I want to write a router that can rewrite my permalinks to .html version and at the same time, not mess us my style (.css) and script (.js) files.

Here is the code which I wrote for my particular use case. You can modify it to suit your requirements.

// router.php

// Get the url path and trim leading slash
$url_path = trim( $_SERVER[ 'REQUEST_URI' ], '/' );

// If url_path is empty, it is root, so call index.html
if ( ! $url_path ) {
    include( 'index.html' );
    return;
}

// If url_path has no dot, it is a post permalink, so add .html extension
if( ! preg_match( '/[.]/', $url_path ) ) {
    include( $url_path . '.html' );
    return;
}

// In case of css files, add the appropriate header
if( preg_match( '/[.css]/', $url_path ) ) {
    header("Content-type: text/css");
    include( $url_path );
    // You can do the same for other file types as well
}

Your router.php is ready. Now, open your terminal, go to the project root and start the PHP server with the following command.

pathtophp.exe -S localhost:8000 router.php

Finally, open your website by going to localhost:8000 on your browser. It works. Great.

Please note that this method is good for small applications so that you can quickly do a test run and check the code without deploying it on a proper server. In the case of bigger applications, this setup may become complicated as it is difficult to scale.

Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *