Django HttpResponseRedirect is http instead of https

My server runs Django + Gunicorn + nginx.

I added an SSL certificate and configured nginx to redirect http to https. When the https request is received, nginx passes it to Gunicorn as http.

My program sometimes returns an HttpResponseRedirect , and the browser receives a redirect response and repeated requests as http, so nginx redirects to https.

How can i avoid this? How to configure the server so that the first redirect points directly to the https URL?

+6
source share
1 answer

In the nginx configuration (inside the location block), specify this:

 proxy_redirect off; proxy_set_header X-Forwarded-Proto $scheme; 

proxy_redirect tells nginx that if the backend returns an HTTP redirect, it should leave it as it is. By default, nginx assumes that the backend is stupid and tries to be smart; if the backend returns an HTTP redirect that says: "redirect to http: // localhost: 8000 / somewhere , nginx replaces it with something similar to http://yourowndomain.com/somewhere ". But Django is not stupid (or it can be set up so that it is not stupid).

Django does not know if the request was executed via HTTPS or plain HTTP; nginx knows this, but the request that it subsequently makes for the Django backend is always simple HTTP. We tell nginx to pass this information with the X-Forwarded-Proto HTTP header, so the corresponding Django functions like request.is_secure() work correctly. You also need to set SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') in settings.py .

+5
source

Source: https://habr.com/ru/post/1013782/


All Articles