Adding expire header for Django static files on Heroku
caching, django, heroku
Solution
The django staticfiles app does not provide out of the box support for custom headers. You'll have to hack together your own view to serve up the files and add custom headers to the HttpResponse.
But You should not be serving your static files using Django. This is a terrible idea.
- Django is single-threaded, and blocking. So every time you're serving a user a static file, you're literally serving nothing else (including your application code, which is what Django is there for).
- Django's staticviews file is insecure, and unstable. The documentation specifically says not to use it in production. So do not use it in production. Ever.
Problem
I'm trying to optimize my webpage and am having trouble setting expiration date headers on my static files. I am running django-1.5, python-2.7.3. Here's my cache settings in settings.pyso far: ``` CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(PROJECT_ROOT, 'cache/'), } } CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = 5 * 60 CACHE_MIDDLEWARE_KEY_PREFIX = '' MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', ... 'django.middleware.cache.FetchFromCacheMiddleware', ) ``` And my static file settings in settings.py: ``` import os.path PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_ROOT = os.path.abspath(os.path.join(PROJECT_DIR, '..')) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles/') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, 'static'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) ``` The closest advice I've found was here, but I'm unable to modify the .htaccess files on Heroku. Any help is greatly appreciated. Thanks!