Scaling Your Frontend: Far-Futures Expire Headers

To optimize our website load times we must optimize the frontend by setting far-futures headers. This simply means that media has an Expires tag of sometime in the distant future (maybe a year), and when we make changes, the filename needs to change. The easiest way to do this, is by adding a simple GET parameter.


We can do this by using a simple template tag (or a global object as it’s known in Jinja), to output the URL to the file, as well as the revision.


import os, os.path
from django.conf import settings
from jinja.contrib.djangosupport import register

def mediaurl(value):
    fname = os.path.abspath(os.path.join(settings.MEDIA_ROOT, value))
    if not fname.startswith(settings.BASE_PATH):
        raise ValueError("Media must be located within MEDIA_ROOT.")
    return '%s%s?%s' % (settings.MEDIA_URL, value, unicode(int(os.stat(fname).st_mtime)))
register.object(mediaurl)

Now to link our media files it’s quick and painless:

<link rel="stylesheet" type="text/css" href="{{ mediaurl('styles/screen.css') }}" />





Although this is a nice way to do it with django, But its far better to set Expire Header at apache level only. This way the request won't come to django and server load will be far less.
To set expire header from apache do proper settings in "httpd.conf" or "htaccess".

	<Location "/flicks/thumbs500">
                SetHandler None
                Header unset ETag
                FileETag None
                Header set Expires "Thu, 15 Apr 2020 20:00:00 GMT"
        </Location>

Hope this will make your website load faster.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Other Posts which you may like:

One response to “Scaling Your Frontend: Far-Futures Expire Headers”

  1. vicky

    Thanks for the good information.

Leave a Reply

Subscribe Me

Google Custom Search