Search code examples
djangonginxwebsocketchanneldaphne

Modify nginx config to reverse proxy websockets properly


Current nginx config:

server {
    listen 443 ssl http2;
    server_name NAME www.NAME;
    charset utf-8;
    ssl on;
    ssl_certificate /etc/nginx/ssl/NAME-cert.pem;
    ssl_certificate_key /etc/nginx/ssl/NAME-key.pem;

    location /static/ {
        alias /home/ubuntu/NAME/static_collection/;
    }

    location /media/ {
    alias /home/ubuntu/NAME/media_collection/;
    }

    location / {
        proxy_pass http://localhost:8002;

    proxy_redirect off;
    proxy_set_header Host $host;
        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;
    }
}

Everything works, apart from the websockets. I suppose this is because it doesn't deal with the http upgrade header... I've looked at the docs, but I can't figure out how to modify this config without breaking anything else.


Solution

  • Try this. Let me know if it works.

    server {
        listen 443 ssl http2;
        server_name NAME www.NAME;
        charset utf-8;
        ssl on;
        ssl_certificate /etc/nginx/ssl/NAME-cert.pem;
        ssl_certificate_key /etc/nginx/ssl/NAME-key.pem;
    
        location /static/ {
            alias /home/ubuntu/NAME/static_collection/;
        }
    
        location /media/ {
        alias /home/ubuntu/NAME/media_collection/;
        }
    
        location / {
            proxy_pass http://localhost:8002;
    
            proxy_redirect off;
            proxy_set_header Host $host;
            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_http_version 1.1;
            proxy_read_timeout 86400;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
        }
    }