Skip to content

Instantly share code, notes, and snippets.

@rogeriopradoj
Last active December 12, 2018 10:54
Show Gist options
  • Select an option

  • Save rogeriopradoj/10645347 to your computer and use it in GitHub Desktop.

Select an option

Save rogeriopradoj/10645347 to your computer and use it in GitHub Desktop.
routing.php - rewrite urls using php built in web server
<?php
// www/routing.php
// http://gonzalo123.com/2012/10/15/how-to-rewrite-urls-with-php-5-4s-built-in-web-server/
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return false;
} else {
include __DIR__ . '/index.php';
}
// cd ./
// php -S localhost:8888 www/routing.php
<?php
// http://www.lornajane.net/posts/2012/php-5-4-built-in-webserver
if (file_exists(__DIR__ . '/' . $_SERVER['REQUEST_URI'])) {
return false; // serve the requested resource as-is.
}
if ($_SERVER['SCRIPT_NAME'] == '/dev.php' ) {
include_once 'dev.php';
} else {
include_once 'index.php';
}
// cd ./www
// php -S localhost:8888 routing.php
@Palivonas
Copy link
Copy Markdown

Provided code will not work when requesting files with query params (which is common for CSS and JS files).
Modifed version that strips the query string:

<?php

function _requestedFileExists ($requestUri) {
	$queryStart = strpos($requestUri, '?');
	if ($queryStart !== -1) {
		$requestUri = substr($requestUri, 0, $queryStart);
	}
	return file_exists(__DIR__ . DIRECTORY_SEPARATOR . $requestUri);
}


if (_requestedFileExists($_SERVER['REQUEST_URI'])) {
	return false;
}

require 'index.php';

@darklightcode
Copy link
Copy Markdown

I've just updated PHP-Built-in-web-server-Router with some fixes for wordpress mostly, you should give it a try if you're planning on using a framework.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment