django 裡判斷請求是否加密

原本以為照著這篇 Django, get scheme (http or https), pre request.scheme implementation 來做,用 request.is_secure() 來判斷就好,但是事情並沒有我想的簡單。

經過簡單的判讀之後,原來是因為我的 django 前面有 nginx 擋著,前面的 nginx 可以處理 HTTPS 沒錯,但是 proxy pass 到 django + gunicorn 這邊之後,由於 proxy_pass 寫的是 http://localhost:8000 ,所以 django 收到的請求還是 HTTP。

後來我是在 nginx 裡,proxy pass 之前,先設定 header,django 裡再改用 header 來判斷,才解決這問題。

# nginx
proxy_set_header X-Forwarded-Proto $scheme;
# django, 參考自 https://stackoverflow.com/questions/14377050/custom-http-header-in-django
scheme = request.META.get('HTTP_X_FORWARDED_PROTO')