Want fresh tech tips in your inbox?

Apache Rewrite Rule for Mapping to index.php in Sub Folders


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 w/ #php #apache #htaccess #urls #mod_rewrite

Apps I've Built

Easily change the location on your photos and videos
Click here for more info about the app
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app