Creating a faux directory structure using mod_rewrite and switch()
The below example is just one way to create a faux directory structure using the magic of Apache’s mod_rewrite and the PHP switch statement.
Sample re-write rules using mod_rewrite. These would be included in your .htaccess file for the directory whose URLs you wish to rewrite. More exacting patterns / rewrite rules are possible.
RewriteEngine On RewriteBase / RewriteRule ^requested_directory$ index.php?page=$0 RewriteRule ^requested_directory/$ index.php?page=$0 RewriteRule ^requested_directory/.*$ index.php?page=$0
Above: ^ starts the beginning of the pattern. $ designates the end of a pattern line. A period indicates ‘any single character.’ the * means ‘0 or N of the preceding text’ (where N is greater than 0).
The stuff after the $ is the replacement request. In this case, we are saying “When requested_directory is requested, get index.php instead.” And when we get index.php, we’re going to pass the requested file/directory as the value for the variable ‘page’. The requested file is the value of $0. It’s a recursive variable. Mod_rewrite rules adhere to regular expression syntax.
A request for http://www.foo.com/requested_directory/bar would be re-written to
http://www.foo.com/index.php?page=requested_directory/bar. Once the URL is rewritten, you can parse it like any other. Here, we’re going to require certain content files based on the value of $_GET['page'] using switch.
<?php
switch($_GET['page']){
case 'requested_directory':
require('../../req_dir_content.inc');
break;
case 'requested_directory/bar';
require('../../bar_content.inc');
break;
default:
require('../../default_content.inc');
}
?>















