HTTPS django-cpserver 和 Nginx 反向代理
最近把内部 blog 也迁移到了 Byteflow, 并在 Webfaction 设置使用 HTTPS 协议.
一般的页面浏览均正常, 但是对于登录 admin 控制台或是保存编辑操作, Django 重定向机制会跳转到 HTTP 协议, 而不是预期的 HTTPS.
内部 blog 也是用 django-cpserver 跑, HTTPS 请求先经由 Webfaction 主 Nginx 反向代理服务器过滤.
由于 Nginx 接管了 HTTPS 加密/解密, 并把用户请求作为普通 HTTP 请求进行转发, 所以 django-cpserver 和 Django 对 HTTPS 一无所知, request.is_secure() 将总是返回 False.
修正方法
用一个简单的 WSGI Middleware 修改请求对象:
class SSLMiddleware(object):
"""
Middleware that applies some fixes for people using
Nginx manage HTTPS and forward requests as HTTP to
backend server.
"""
def process_request(self, request):
# use HTTPS forever
request.is_secure = lambda: True == True
将以上代码保存成 .py 文件, 并追加到 Django settings.py 文件 MIDDLEWARE_CLASSES 元组中, 重启后台服务器生效.






2 Comments Subscribe comments
request.is_secure = lambda: True == True 能解释一下这里lambda的意思吗?我直接设置request.is_secure=True就会报错的
lambda 用来定义一个单行匿名函数, request.is_secure 则是一个函数指针. Django 会通过调用 request.is_secure() 来判断是否是 https 协议.
Leave a Reply You can use reStructuredText here.