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.