反向代理后面带有HTTPS的build_absolute_uri

时间:2020-05-27 15:52:12

标签: django nginx gunicorn

我在反向代理后面提供我的Django应用

互联网-> Nginx-> Gunicorn套接字-> Django应用

在nginx配置中:

upstream my_server {
  server unix:/webapps/my_app/run/gunicorn.sock fail_timeout=0;
}

使用certbot在nginx级别上设置SSL。

request.build_absolute_uri中的

views.py生成http链接。如何强制它生成https链接?

3 个答案:

答案 0 :(得分:3)

默认情况下,Django 忽略所有 X-Forwarded 标头,基于 Django docs.

通过设置 X-Forwarded-Host 和设置 USE_X_FORWARDED_HOST = True 强制读取 SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') 标头。所以在settings.py

USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

答案 1 :(得分:0)

django文档https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpRequest.build_absolute_uri中有一条注释:

Mixing HTTP and HTTPS on the same site is discouraged, therefore build_absolute_uri() will always generate an absolute URI with the same scheme the current request has. If you need to redirect users to HTTPS, it’s best to let your Web server redirect all HTTP traffic to HTTPS.

答案 2 :(得分:0)

我在 apache2 后面使用 django,所以我的解决方案是把它放在 apache2 上

<VirtualHost *:443>
  RequestHeader set X-Forwarded-Proto 'https' env=HTTPS

添加标题后:

a2enmod headers

这在 django setting.py 上:

USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

有了这个,我所有的 build_absolute_uri 都是从 https 开始的