Written by Sean Behan on Fri Oct 20th 2017

Below is an example URL structure with rewrite rules using an Apache .htaccess file.

GET /a/       => a/index.php
GET /a/b/     => a/b/index.php
GET /a/b/c/   => a/b/index.php

This URL mapping will give you pretty URLs in PHP without needing to route all requests through a single PHP file or "front controller" pattern.

Each sub folder will have it's own index.php file, thus avoiding the need to use .php extension and pass argument info via query params (not that there is anything wrong with that!).

The PHP development server php -S localhost:5000 behaves this way too, so you can easily achieve development and production parity.

Pop this into an .htaccess file in the document root of your project.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# 3 levels deep
# GET /a/b/c-some-thing-here    
RewriteRule (.*)/(.*)/(.*) /$1/$2/index.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# 4 levels deep
# GET /a/b/c/d-some-thing-here
RewriteRule (.*)/(.*)/(.*)/(.*) /$1/$2/$3/index.php [L]

Note that this rewrite rule does not work with arbitrary directory depths. You will have to add more rules to handle deeper folder structures.

I haven't spent too much time on it but should be possible to write a regex that will capture and map an entire folder path (minus the last segment) to relative file path of an index.php file!


Tagged with..
#php #apache #htaccess #urls #mod_rewrite

Just finishing up brewing up some fresh ground comments...