Saturday, March 2, 2013

Caching HTTPS Static Files in Django

This post assumes you are familiar with the django staticfiles app and are already serving your static files from a different server that's optimized for serving static files.

Caching static files in the browser is an important technique for speeding up page load times. Part of the challenge in getting this right is that many of the parts are dependent on each other.

For my needs, the webpage needed to be served using HTTPS. To avoid the dreaded "mixed content" warning messsage, this meant that all of the supporting static files would also need to be served using HTTPS.

I serve my static files from a shared server on webfaction. My choices are an nginx server where my options as to set cache expires to the max or not at all. The other choice is an Apache server with htaccess controls.

The first question was, what cache controls are needed to cache HTTPS files? Some authors claim it is necessary to set cache-control:public to get the browser to cache HTTPS. If this were the case, then I would need to go with the Apache server. Evidently, that is an old recommendation. According to stackoverflow, its no longer needed as of 2010. Maybe I can still use nginx.

If I am going to use nginx, then the problem is how to update static content when the browser cache is really long. Luckily some clever Django app developers have this all figured out. They have made it possible to have collectstatic put a hash of the file content in to the filename. Thus every time you change the content, a new file is created which will cause the browser to download it and cache it.

But wait, won't changing the filename mess up my templates? Not to worry, the app the adds the hash to the filename, keeps a mapping between the original name and the new name. When a template is  rendered, the app changes the names to the new names. For more info, check out class storage.CachedStaticFilesStorage .

No comments:

Post a Comment