在Django中缓存静态文件
我在用谷歌的Page Speed插件给我的网页应用做性能分析时,发现它提到我应该“利用缓存”。具体来说,它说“以下可以缓存的资源新鲜度时间太短。请为以下资源指定一个至少在未来一周的过期时间”。我进一步调查后发现,所有对Django WSGI服务器的静态文件请求都缺少Expires
和Cache-Control
这两个头信息。那这些头信息应该由谁来添加呢?是Django来做吗?如果是的话,应该怎么做呢?
谢谢。
1 个回答
7
你网页上用到的任何静态文件,比如图片、样式表等,都应该由你的网络服务器来提供,比如Apache。除非你需要限制某些人访问某些文件,否则Django不应该参与这个过程。
这里有一个示例,教你怎么做:
# our production setup includes a caching load balancer in front.
# we tell the load balancer to cache for 5 minutes.
# we can use the commented out lines to tell it to not cache,
# which is useful if we're updating.
<FilesMatch "\.(html|js|png|jpg|css)$">
ExpiresDefault "access plus 5 minutes"
ExpiresActive On
#Header unset cache-control:
#Header append cache-control: "no-cache, must-revalidate"
</FilesMatch>