nginxwebsocketnginx-reverse-proxynginx-configcertbot

Setup websocket nginx proxy to node.js using ssl from certbot


I want to us ssl websockets (wss://) with my node application that is using the ws npm module. On top of it I want to use the ssl that I set up with nginx from certbot.

I have the node websocket listening on port 8080, and while I can connect directly to that, since the site is being served via ssl, that causes an error to be thrown since it isn't encrypted.


Solution

  • For the client side javascript, you can route your calls to wss://examplesite.com/websocket

    
    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }
    
    upstream websocket {
       server 127.0.0.1:8080;
    }
    
    server {
        server_name examplesite.com;
        location /websocket {
                proxy_pass http://websocket;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection $connection_upgrade;
                proxy_set_header Host $host;
        }
    
    # after this is just an example of the rest of the nginx config for a node server on 8675
    # that has a static build directory
        location / {
            proxy_pass http://127.0.0.1:8675;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header X-Real-IP $remote_addr;
        }
        location ~ \.(gif|jpg|png|js|txt|html|mp3|css|woff2)$ {
            root /root/examplesite.com/build/;
            expires 30d;
        }
    
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/examplesite.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/examplesite.com/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    
    }
    

    You can use https://www.npmjs.com/package/wscat to test out your local ws://...:8080 and your wss://.../websocket connection