0
votes

I set up an nginx/gunicorn server with this tutorial. This worked like a charm with a local docker-compose file. Then I pushed the containers to AWS fargate, and set up a load balancer in front of the nginx. This worked too, but I got a "CSRF failed" exception, when trying to login to django admin.

This is because the host, port and protocol are not correctly forwarded from the user request though the load balancer and the nginx proxy to django gunicorn.

How do I have to configure nginx and django?

1

1 Answers

1
votes

I ended up with this nginx configuration, which works behind a load balancer and with my local docker-compose config, where the user directly requests to nginx. rg_ is just the prefix for my project.

# Set proto and port to forwarded value, or to nginx value if
# forwarded value not set
map $http_x_forwarded_proto $rg_forwarded_proto {
    default $scheme;
    "~^(.*)$" $1;
}

map $http_x_forwarded_port $rg_forwarded_port {
    default $remote_port;
    "~^(.*)$" $1;
}

# Gunicorn proxy
upstream rg_serve {
    server localhost:8100;
}

# Server
server {

    listen 8090;

    location / {
        proxy_pass http://rg_serve;

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header X-Forwarded-Proto $rg_forwarded_proto;
        proxy_set_header X-Forwarded-Port $rg_forwarded_port;

        proxy_set_header X-Forwarded-Host $host:$rg_forwarded_port;

        proxy_redirect off;
    }

    location /static/ {
        alias /home/app/rg_serve/web/static_collect/;
    }    

}

I have to set

USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

in my django settings, to make it work.

What feels a bit strange is, that I have to add the port to X-Forwarded-Host to make it work in django. When I just do not add it, and set django settings to

USE_X_FORWARDED_HOST = True
USE_X_FORWARDED_PORT = True 
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

Is does not work. I get the csrf exception.