Saturday, December 8, 2007

Updated ZF .htaccess

A while back, I talked about how to setup a bootstrap on Apache to use with ZF. Since then, I've made a few modifications to my .htaccess file that I think are worth documenting.

First of all, I ran into a problem where flash files were referencing other binary files (.swf and .flv) relatively. But with ZF's URL rewriting, this was getting totally messed up, and only certain components of Flash objects were showing up. The fix I needed was in the .htaccess RewriteRules. The new rules I have are like so.

RewriteEngine on
RewriteBase /

RewriteRule !\.(js|ico|gif|jpg|png|css|flv|swf)$ index.php

Of course, if I had read the updated ZF documentation, I would have already known that.

Another "fix" I've used in my .htaccess file has to do with caching. Back in the day when websites were static, site-wide .css files were great. Not only did it allow for updating the entire site in one place, but it allowed browsers to cache the CSS so downloading pages that used it was even faster.

Problem: What if you add a feature to your site which requires new style rules. Since browsers have cached the .css file, any updates to it won't be seen until either the browser decides to refresh its cache or the user specifically Refreshes. Having that designer blood in me, I just can't stand the thought that some people will view that new feature without having the styles for it.

I came up with a bunch of ways to fix this, and they all suck in one way or another. One method that is particularly appealing to me as a programmer is to ditch browser-level caching by making everything a page style (in a style tag in the head of every page). This way, when a browser gets updates to a page, it will also get the updates to the CSS, and they will always be in sync. If you want to keep the ability to change one thing and change the whole site, simply move common CSS rules into a separate file which is included by your PHP.

The way we ended up doing it though — since my designer wanted to avoid PHP as much as possible — was with a .htaccess modification. The idea was that we wanted to disable browser-level caching of .css files. So I added the following to our .htaccess file which tells browsers to only cache .css files for 5 minutes.

<IfModule mod_headers.c>

# Cache library files for 5 minutes
<FilesMatch "\.css$">
Header set Cache-Control "max-age=300"
</FilesMatch>

</IfModule>

The nice thing about this is Apache simply adds a header to all your .css files without you having to modify anything in your code.

1 comment:

Anonymous said...

Handling file and directory exceptions

These rules (used immediately prior to the RewriteRule above) exclude real files and directories from the rewriting and lets them pass through unaffected:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d