Question

I have a django/mezzanine/django-cumulus project that uses the rackspace cloudfiles CDN for media storage. I would like to automatically serve all static files from the local MEDIA_ROOT, if they exist, and only fallback to the CDN URL if they do not.

One possible approach is to manage the fallback at the template level, using tags. I would prefer not to have to override all the admin templates (eg) just for this, however.

Is there a way to modify the handling of all media to use one storage engine first, and switch to a second on error?

Was it helpful?

Solution 2

Based on Anup's suggestion, I found that this bit of nginx config nicely handles the 404 condition:

location /static/ {
    root            /path/to/static_root;
    # ...
    error_page 404 =  @cdn;
}

location @cdn {
    # cdn_cname.example.com is an alias for deadbeef012345.r99.cf5.rackcdn.com
    rewrite ^/(.*)$ http://cdn_cname.example.com/$1 last;
}

This will correctly redirect any request for a /static/ URI that returns 404 on the local server to the CDN. However, django-cumulus still renders links to static files via the CDN. To fix that, I added the following to the CUMULUS block of settings.py:

CUMULUS {
    # ...
    'CONTAINER_URI': 'http://example.com/static',
}

Now, django-cumulus links use the local server's static URI, which will hit the nginx configuration above, and only redirect to the CDN when necessary. Hooray!

OTHER TIPS

The best way is to have this working, is to have a different web server serving all of your media (I used nginx). Then you setup a load balancer to detect failure and redirect all the requests to CDN in case of a failure. One thing that you might have to figure out is the image path.(use HAProxy to rewrite the request URL, if you need to)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top