Search code examples
djangonginxproxywebsocketdaphne

Proxy redirecting websockets and http to the same (unix) socket


I've made a little nginx conf to redirect trafic to a unix socket listened by a daphne server (server used for django).

According to the documentation :

If you use Daphne for all traffic, it auto-negotiates between HTTP and WebSocket, so there’s no need to have your WebSockets on a separate port or path

So I'd like to proxy both websockets and Http trafic to the same unix socket.

  1. Is it possible?

  2. How could I do?

Here is what I tried thus far :

upstream django_ws {
         server unix:///path/to/ws.sock;
}

server {
       listen 8082;
       server_name 127.0.0.1;
       charset utf-8;

       root /path/to/root;

       set $myroot $document_root;

       location / {
                proxy_pass http://django_ws;
                #proxy_http_version 1.1;
                #proxy_set_header Upgrade websocket;
                #proxy_set_header Connection upgrade;
       }
}
  • If I uncomment the lines in the location bloc, the page appears blank.

  • If I don't, the pages appear but the websockets don't seem to work.

How could I solve this?

Everything works fine with the development server.


Solution

  • I found a solution :

    I instanciate my websockets like this :

    var socket = new WebSocket(ws_scheme + "://" + window.location.host
                               + "/ws" + window.location.pathname);
    

    So I can just separate request coming to /ws and requests coming to /.

    So I just did this :

    upstream django_ws {
             server unix:///path/to/ws.sock;
    }
    
    server {
           listen 8082;
           server_name 127.0.0.1;
           charset utf-8;
    
           root /path/to/root;
    
           set $myroot $document_root;
    
    
           location /ws {
                    proxy_pass http://django_ws;
                    proxy_http_version 1.1;
                    proxy_set_header Upgrade websocket;
                    proxy_set_header Connection upgrade;
           }
    
           location / {
                    proxy_pass http://django_ws;
           }
    }
    

    and it worked just fine!