如何将SECURE_SSL_REDIRECT与Cache-Control标头一起使用?

时间:2016-02-19 16:23:50

标签: django

我在django部署的设置中启用了SECURE_SSL_REDIRECT,所以现在这些标头已发送到客户端了:

< HTTP/1.1 301 MOVED PERMANENTLY
< Date: Fri, 19 Feb 2016 15:57:50 GMT
< Server: Apache/2.2.15 (Red Hat)
< Location: https://www.example.com/
< Content-Length: 0
< Content-Type: text/html; charset=utf-8

301重定向的主要缺点是它们往往被浏览器缓存很长时间,因此我非常希望为此添加Cache-Control: max-age=604800, must-revalidate标头。我希望这种方式不涉及重新实施SECURE_SSL_REDIRECT

1 个答案:

答案 0 :(得分:1)

您可以尝试覆盖Django的SecurityMiddleware以添加所需的http标头。以下是中间件的完整实现:​​

class CustomSecurityMiddleware(SecurityMiddleware):

    def process_request(self, request):
        response = super(CustomSecurityMiddleware, self).process_request(request)

        # SecurityMiddleware returns an HttpResponsePermanentRedirect only if 
        # the request should be redirected
        if response is not None:
            response['Cache-Control'] = 'max-age=604800, must-revalidate'
            return response

此实现保留了Django SecurityMiddleware已经完成的所有功能,同时添加了您需要的自定义http标头。

自定义中间件应取代settings.MIDDLEWARE_CLASSES中的SecurityMiddleware。