Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amazon ELB + Django HTTPS issues

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?

like image 794
psychok7 Avatar asked Oct 23 '25 19:10

psychok7


1 Answers

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

like image 70
Tarun Lalwani Avatar answered Oct 26 '25 09:10

Tarun Lalwani