The .htaccess file I use for all my apache projects

Haven’t given blogging a shot yet but my coffee is getting to me so I’ll give it a whirl. Here’s the .htaccess file I use for every one of my PHP projects:

// .htaccess (same directory as index.php)
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*)$ /PATH_TO_PROJ_DIR/index.php?path=$1 [NC,L,QSA]
Options -Indexes

If you don’t know what a .htaccess file is, you can read about it here. Among other things, its a way to make your URLs beautiful, but if you use it the right way it lets you add a nice layer of abstraction between how your client uses your API and how the app operates.

Some background: I’m not a huge fan of backend frameworks (Rails, Codeignitor, Django, Zendphp, Laravel, CakePHP, Symphony). If you know a language well, and if you are using the right language, you can do anything any framework lets you do in a couple of lines of code– you just need to think about it the right way. I like to think of using PHP as a framework (I didn’t invent this idea). Here’s a starter template I built in PHP that mirrors the django project setup (I love the simplicity):

The .htaccess file above routes everything to index.php and makes everything before the url parameters available at $_GET[“path”].

Here’s an ex:


In index.php:

// index.php 

spits out:

// http://localhost:8888/this/is/the/path?param=jake&param2=php+is+awesome
[path] => this/is/the/path
[param] => jake
[param2] => php is awesome

Now in index.php we can reference a function by name based on the given path, which is just a String.

Since php has support for variable functions (read more here), you can do this:

// index.php
$method = $_GET["path"];
(figure out what file to include and include it)
unset($_GET["path"]); // get rid of the path once we used it
$method($_GET); // include the $_GET as params

There you go! Here’s a “php micro framework” that does the same thing but makes you learn how to speak Vulcan first.

And finally, from the maker of PHP Rasmus Lurdorf himself: