Error during WebSocket handshake: Unexpected response code: 301

Tobias Gassmann picture Tobias Gassmann · Aug 11, 2018 · Viewed 11.1k times · Source

I have already looked into the answer to RoR 5.0.0 ActionCable wss WebSocket handshake: Unexpected response code: 301 but it was not applicable to my case.

I use an nginx-proxy as a front for several web-servers running in docker-containers. I use the nginx-config-template from https://github.com/jwilder/nginx-proxy

Now in my docker-container I have another nginx with the following config:

map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

upstream websocket {
    server my-websocket-docker-container:8080;
}

server {
    root /src/html;


    location /websocket/ {
        resolver 127.0.0.11 ipv6=off;
        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    ...

}

When trying to connect to wss://example.com/websocket I get the aforementioned error about unexpected response code 301. When I curl the websocket-url manually I can see the nginx response telling me "301 moved permanantly". But why? Where is this coming from?

Can anybody help? Thanks!

Answer

LoolKovsky picture LoolKovsky · Jan 12, 2021

I was facing a similar issue today. I was using the "classic" WebSocket API and NGINX to test the connection between some services. I came up with the following solution:

WebSocket instance creation:

const websocket = new WebSocket('ws://' + window.location.host + '/path');

Nginx config:

location /path {
    proxy_pass http://websocket:port;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

Where:

  1. path is the path to be redirected
  2. websocket is the hostname or the IP of the host
  3. port is the port where the application is served on the host