August 25th, 2011

  • Technology

Custom Directory Listings with Htaccess

It never ceases to amaze me how incredibly powerful and misunderstood the .htaccess file is to web developers.  Most of us never need to crack open that file, but if we do, a quick Google search will give you all the code you need.

Last night I was thinking about a presentation server I use at work.  Every folder has a custom PHP file in it to display the contents of the folder in a prettier way than the standard Apache directory listing.  I‘m tired of having to copy that index.php into every directory.  There had to be a better way.  Having worked with ExpressionEngine and CodeIgniter I knew you can take URL segments and use them as variables and if I can do that then I can easily pass them into another file without the user even noticing.

My solution to this problem is:

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteCond %{REQUEST_FILENAME}/index.html !-f
RewriteRule ^(.*)$ /custom.php?q=$1

This first line checks to see if the url is a folder on the server, e.g., example.com/folder/.  The second line ensures all request for files are excluded from this rule.  The third and forth lines skip directories that contains an index.html or index.php file because if I have a website mockup in that folder I don’t need a custom directory listing.  Finally if the the url meets all those criteria it sends the folder path to custom.php as a query string.  From there I can do whatever I need to.  Hopefully now if you ever need to do something similar, Google can send you here.