DEV Community

Victor R.
Victor R.

Posted on

Improving redirects in PHP Built-in Webserver

This issue arose when I tried using a period in my parameters within my REST API. One could question the point of this, but let's assume there's a good solid business reason for it.

This is the sample url:


This url works absolutely fine on nginx and apache. However the built in php server, when it sees a dot / decimal / period in the url, it tries to find the file. So attempting to access this url on the PHP built-in web server results in: was not found on this server

The way to change the default behaviour of the built-in server is to add a custom router script. I found this online in a stack overflow post... after much, much searching:


$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

if (file_exists($_SERVER['DOCUMENT_ROOT'] . $path)) {
    return false;
} else {
    $_SERVER['SCRIPT_NAME'] = 'index.php';
    include './public/index.php';
Enter fullscreen mode Exit fullscreen mode

I am running the API from a ./public folder, index.php, as you can see in the above code. This script checks if an actual file exists at the requested url, and if not redirects by default to the public/index.php, which is what we want.

Adding in a router however changed how php handles paths, so this code:

require '../flight/Flight.php';

No longer worked with the router.php in play. I had to change it to the following:

require __DIR__ . '/../flight/Flight.php';

Now to run the built in web server, keeping in mind that the router.php file is in the project root, and I run this from the root:

php -S -t public router.php

(i prefer so i can access the site from my phone on same LAN)

Hope this helps others out there that may run into the same issue.

Top comments (2)

yellow1912 profile image

Nice. Are you using the server for testing purposes or in production?

crazedvic profile image
Victor R.

Sorry for delay for some reason I don't get notified of comments. Will look into this. I am using this server for development locally. In production I use nginx and I don't have that issue there. Generally I prefer to use phpStorm with autodeployment via sftp to send code updates to my staging server on the fly. This lets my front end developers get changes in real time as I fix or add features. And most of the time I actually test my REST calls from POSTMAN against staging. I only use local development server for brand new code features that could break stuff, and i have auto-deploy turned off. Hth.