3

I have been searching on SO but none of the solutions seem to work for my case:
I have a Classic Elastic Load Balancer from AWS, passing requests to my Nginx docker containers that also proxy passes to my python Gunicorn containers.

Nginx config:

server {
    listen 80;
    listen [::]:80;
    ...

    if ($http_x_forwarded_proto = 'http') {
        return 301 https://$server_name$request_uri;
    }

    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://app_server;
    }
 }

In my Django Settings I have :

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = False

The problem is, when a request is made to an endpoint, if I print(request.META.get('HTTP_X_FORWARDED_PROTO')) I get http instead of https. This causes my DRF auto-generated doc links to be generated in http instead of https.

Is there something wrong with my configurations?
How can I force https behind an ELB?

psychok7
  • 5,373
  • 9
  • 63
  • 101
  • 1
    Why don't you just add `proxy_set_header X-Forwarded-Proto https;` in your nginx config? Your nginx will always be serving the clients using https...right? – Tarun Lalwani May 17 '18 at 12:38
  • i edited my question with the rest of my configuration for that part. so basically i already had it. – psychok7 May 17 '18 at 15:53
  • @TarunLalwani looks like your advice ended up fixing my issue. i did proxy_set_header X-Forwarded-Proto https; and it now works. for some reason $scheme did not seem to set it as https any idea why? nevertheless if you make an official answer ill mark it as the correct answer – psychok7 May 17 '18 at 19:34

2 Answers2

6

Just add

proxy_set_header X-Forwarded-Proto https; 

in your nginx config. Your nginx will always be serving the clients using https as the ELB is configured to receive https traffic.

Also the reason $scheme may not have worked is because your nginx is still on http protocol and not https protocol

Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
0
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;
davesave
  • 2,863
  • 1
  • 18
  • 13