Apache's fallbackresource: your new .htaccess command

Warning: This blogpost has been posted over two years ago. That is a long time in development-world! The story here may not be relevant, complete or secure. Code might not be complete or obsoleted, and even my current vision might have (completely) changed on the subject. So please do read further, but use it with caution.
Posted on 21 Jan 2012
Tagged with: [ apache ]  [ rewrite

So probably you are aware I’m currently exploring the deeps on the Apache source internals. One of the discoveries I’ve made was a (for me unknown) command in mod_dir that will make your life a little bit easier: fallbackresource. 

One of the things that most frameworks do nowadays is to rewrite all URL’s to a single entry point. This entry-point (sometimes called the front-controller), will decide how the request is handled (which controller gets called, if it needs authorization first etc). However, some files, like images, css or javascript files can be fetched directly. It is a bit pointless to rewrite those URL’s to the front-controller.

Now, normally this would mean you need Apache to configure to rewrite “non-existing” URL’s to the front controller. This is done with a .htaccess:

    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]

This will check if the requested filename either exists or is a directory, if that is NOT the case, it will call the file index.php (the [L] means this is the last match that needs to be made, if there are my rewrite-rules present, they will be skipped).

Now this is all nice, but a little fragile. It’s easy to mess things up (as I do on occasion) but there is another command that does the same thing with only one command:

FallbackResource /index.php

This would be exactely the same as the rewriting seen above, but with less time to create typo’s. Funny enough, it’s not part of mod_rewrite, but of mod_dir and is available from Apache 2.2.16 and above.

If you want to do a little bit more exotic stuff, like if you need to use rewriteBase, or maybe have different rewrite conditions, you must stick with the mod_rewrite rules, but most of the time, the fallbackresource will suffice.