Home > Net >  How to host websocket behind nginx reverse proxy
How to host websocket behind nginx reverse proxy

Time:04-14

On my VPS I only have one port and this is the reason why I use proxer - a dockerized nginx reverse proxy where you provide domain names and local ports to which it should be redirected.

I have successfully set up socket.io server with polling transport (as it uses http methods) but I would like to use websocket transport and this is where it fails. It tells me it can't estabilish wss:// connection to this url.

This is nginx reverse proxy code I am using:

for cfg in $(cat /config); do
    domain=$(echo $cfg | cut -f1 -d=)
    destination=$(echo $cfg | cut -f2 -d=)
    echo ">> Building config for $domain";

    config=$(cat <<EOF
server {
    listen       80;
    listen  [::]:80;
    server_name  $domain;
    location / {
        proxy_pass $destination;
        proxy_set_header Host \$host;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        #proxy_set_header Connection \$connection_upgrade;
        proxy_ssl_name \$host;
        proxy_ssl_server_name on;
        proxy_ssl_verify off;
        proxy_ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
        proxy_ssl_session_reuse off;
        proxy_set_header X-Forwarded-For \$remote_addr;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_read_timeout 120;
        proxy_send_timeout 120;
        proxy_connect_timeout 120;
    }
}
EOF
)
    
    # append new config to the end of nginx config file
    echo "$config" >>$out
done

I noticed that this line is commented out and I read that it is needed for wss://:

#proxy_set_header Connection \$connection_upgrade;

Why is it commented out? Will changing this line affect http proxy? What changes should I do to allow wss:// on one of domains

CodePudding user response:

This tool has pretty much everything what is needed to set up nginx reverse proxy.

Note that it won't support wss:// out of the box though due to this commented line in its config.

#proxy_set_header Connection \$connection_upgrade;

Uncomment it, rebuild and have a happy reverse proxy which supports wss:// :)

  • Related