Django Statics on CloudFront via S3

If you want to offload your static file hosting to CloudFront, have a look at the snippet below. It's currently powering we20.org. You'll need to adjust it to your own file layout.

Requires s3-cmd.

First we need pre-gzip our content. [CloudFront won't do it for us.] Then have the script grab our svn rev number and push all our content to S3 in a folder of that name. We need to have the rev. number in the URL, as CloudFront can take up to 24hrs to refresh content from S3.

#!/bin/sh
cd ~/live.we20.org/static
 
svn update .
 
export AWS_ACCESS_KEY_ID=???
export AWS_SECRET_ACCESS_KEY=???
 
BUCKET=we20.org-static
#Your bucket
PREFIX=`svn info . | grep "Revision" | awk '{print $2}'`/
#If you want to use prefix set it like PREFIX=blog/ 
S3CMD=/usr/share/s3sync/s3cmd.rb
#Your absolute path to s3cmd.rb
 
find * -type f   -name \*.css -exec sh -c "gzip -9 -c {} > /tmp/s3tmp && \
        $S3CMD -v put $BUCKET:$PREFIX{} /tmp/s3tmp x-amz-acl:public-read Cache-Control:max-age=604800 Content-Type:text/css Content-Encoding:gzip" \;
 
find * -type f   -name \*.js -exec sh -c "gzip -9 -c {} > /tmp/s3tmp && \
        $S3CMD -v put $BUCKET:$PREFIX{} /tmp/s3tmp x-amz-acl:public-read Cache-Control:max-age=604800 Content-Type:application/x-javascript Content-Encoding:gzip" \;
 
find * -type f   -name \*.png -exec $S3CMD -v put $BUCKET:$PREFIX{} {} \
    x-amz-acl:public-read Cache-Control:max-age=604800 Content-Type:image/png \;
 
find * -type f   -name \*.gif -exec $S3CMD -v put $BUCKET:$PREFIX{} {} \
    x-amz-acl:public-read Cache-Control:max-age=604800 Content-Type:image/gif \;
 
find * -type f   \( -name \*.jpg -o -name \*.jpeg \) -exec $S3CMD -v put $BUCKET:$PREFIX{} {} \
    x-amz-acl:public-read Cache-Control:max-age=604800 Content-Type:image/jpeg \;
 
echo MEDIA_URL=\"http://static.we20.org/$PREFIX\" &> ~/live.we20.org/projects/live_env/static.py

This will also generate a file static.py, which you'll import into your settings.py to set MEDIA_URL to your fresh statics.

P.S. I borrowed much of this from Mudy's solution for Wordpress.