Django的HttpResponseRedirect是http而不是https

per*_*ike 9 django https redirect nginx

我的服务器运行Django + Gunicorn + nginx.

我添加了SSL证书并配置了nginx以将http重定向到https.当收到https请求时,nginx将其作为http传递给Gunicorn.

我的程序有时返回HttpResponseRedirect,浏览器获得重定向响应并重新请求为http,因此nginx重定向到https.

我怎么能避免这个?如何配置服务器以使第一个重定向直接指向https URL?

Ant*_*des 10

在nginx配置中(在location块内),指定:

proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
Run Code Online (Sandbox Code Playgroud)

proxy_redirect告诉nginx的是,如果后端返回一个HTTP重定向,它应该保留原样.默认情况下,nginx假设后端是愚蠢的并且试图变得聪明; 如果后端返回一个HTTP重定向,表示"重定向到http:// localhost:8000/somewhere ",nginx将其替换为与http://yourowndomain.com/somewhere类似的内容.但Django并不愚蠢(或者它可以配置为不是傻瓜).

Django不知道请求是通过HTTPS还是普通HTTP发出的; nginx知道这一点,但随后它对Django后端的请求总是纯HTTP.我们告诉nginx使用X-Forwarded-ProtoHTTP头传递此信息,以便相关的Django功能request.is_secure()正常工作.你还需要设置SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')你的settings.py.