proxying websockets via nginx and https
This is the nginx configuration I use to put a Node.js WebSocket app behind HTTPS. The app listens on a local port (4050 here) and only speaks plain WebSocket. nginx handles the SSL certificate, so browsers can connect securely with wss://, and the app never has to deal with TLS itself. How it works The map block sets a $connection_upgrade variable. When a browser sends an Upgrade header, which is how every WebSocket connection starts, the value is upgrade. For ordinary requests it’s close. The upstream block names the app websocket and points it at 127.0.0.1:4050, so the app’s port is only reachable through nginx. The server block listens on port 443 with the site’s certificate and key. The log and certificate paths are the ones used by the control panel on that server, so adjust them for yours. location / is where the WebSocket proxying happens. proxy_http_version 1.1 is required because WebSockets need HTTP/1.1. The two proxy_set_header lines pass the Upgrade and Connection headers on to the app; without them nginx drops those headers and the handshake fails. Host passes the original domain through. The script-file location sends requests ending in .php, .py and similar to the same port, using the panel’s standard proxy settings from proxy.inc. The .ht, .git, .svn, .hg and .bzr locations block access to hidden config files and version-control folders. The /.well-known/acme-challenge location lets AutoSSL or Let’s Encrypt verify the domain, so the certificate keeps renewing. Using it Replace DOMAIN.com, the listen IP (172.31.83.59) and the port 4050 with your own values. Test the configuration with nginx -t and reload nginx. Your front end can then connect with new WebSocket("wss://DOMAIN.com/"). ...