[Fixed]-Build_absolute_uri with HTTPS behind reverse proxy

28๐Ÿ‘

โœ…

By default Django ignores all X-Forwarded headers, base on Django docs.

Force read the X-Forwarded-Host header by setting USE_X_FORWARDED_HOST = True and set SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https'). So in settings.py:

USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
๐Ÿ‘คAli ZahediGol

1๐Ÿ‘

I use django behind apache2 so my solution was to put this on apache2

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

After adding headers mod:

a2enmod headers

And this on django setting.py:

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

With this all my build_absolute_uri started with https

๐Ÿ‘คuser3486626

-1๐Ÿ‘

Thereโ€™s a note in the django documentation here 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.

๐Ÿ‘คAlex

Leave a comment