2

I am using Django to serve static files (dev, localhost only). I want these files to be cached by the browser, but they aren't. I therefore added Middleware to change the response header for /static/ urls as described here Turn off caching of static files in Django development server (They were fixing the opposite issue, but also by changing the header).

The issue is that the files are still not being cached. I believe this is because of the 'Vary: Cookie' header. How do I get rid of this header? It seems to be added sometime after my Middleware StaticCache is executed.

Response header of static files in browser:

Cache-Control:public, max-age=315360000
Content-Length:319397
Content-Type:application/javascript
Date:Mon, 22 Aug 2016 13:34:04 GMT
Expires:Sun, 17-Jan-2038 19:14:07 GMT
Last-Modified:Fri, 19 Aug 2016 23:18:48 GMT
Server:WSGIServer/0.1 Python/2.7.10
Vary:Accept-Encoding, Cookie

settings.py

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    '<app>.middleware.BeforeViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    '<app>.middleware.StaticCache', 
    '<app>.middleware.ExceptionMiddleware',
)

middleware.py

class StaticCache(object):
    def process_response(self, request, response):
        if request.path.startswith('/static/'):
            response['Cache-Control'] = 'public, max-age=315360000'
            response['Vary'] = 'Accept-Encoding'
            response['Expires'] = 'Sun, 17-Jan-2038 19:14:07 GMT'
        return response

urls.py

url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
Community
  • 1
  • 1
user984003
  • 28,050
  • 64
  • 189
  • 285

1 Answers1

2

I believe that the Vary: Cookie header is set by the SessionMiddleware. Since the response middlewares run in reverse order, you should put your StaticCache middleware before the session middleware in your MIDDLEWARE_CLASSES setting.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • I have not tested this yet because I ended up solving it a different way (got default cache to work with static files), but will leave it here for others. Thanks! – user984003 Aug 22 '16 at 14:31