将操作系统环境变量 HTTPS 设置为 on
您需要启用操作系统环境变量HTTPS
to 'on'
所以 django 会在完全生成的链接前面添加 https(例如,像HttpRedirectRequest
s)。如果您使用 mod_wsgi,则可以添加以下行:
os.environ['HTTPS'] = "on"
to your wsgi脚本 http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango。您可以通过阅读了解这样做的必要性django/http/__init__.py
:
def build_absolute_uri(self, location=None):
"""
Builds an absolute URI from the location and the variables available in
this request. If no location is specified, the absolute URI is built on
``request.get_full_path()``.
"""
if not location:
location = self.get_full_path()
if not absolute_http_url_re.match(location):
current_uri = '%s://%s%s' % (self.is_secure() and 'https' or 'http',
self.get_host(), self.path)
location = urljoin(current_uri, location)
return iri_to_uri(location)
def is_secure(self):
return os.environ.get("HTTPS") == "on"
保护您的 cookie
In 设置.py https://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-secure把线
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
并且 cookie 只会通过 HTTPS 连接发送。此外,您可能还想要SESSION_EXPIRE_AT_BROWSER_CLOSE=True
。请注意,如果您使用旧版本的 django(低于 1.4),则没有安全 CSRF cookie 的设置。作为一个快速修复,您可以在会话 cookie 安全时让 CSRF cookie 安全(SESSION_COOKIE_SECURE=True
),通过编辑django/middleware/csrf.py
:
class CsrfViewMiddleware(object):
...
def process_response(self, request, response):
...
response.set_cookie(settings.CSRF_COOKIE_NAME,
request.META["CSRF_COOKIE"], max_age = 60 * 60 * 24 * 7 * 52,
domain=settings.CSRF_COOKIE_DOMAIN,
secure=settings.SESSION_COOKIE_SECURE or None)
将 HTTP 请求定向到 Web 服务器中的 HTTPS
接下来,您需要一个将 http 请求重定向到 https 的重写规则,例如在 nginx 中
server {
listen 80;
rewrite ^(.*) https://$host$1 permanent;
}
姜戈的reverse
function 和 url 模板标签仅返回相对链接;因此,如果您在 https 页面上,您的链接将使您保持在 https 网站上。