Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error during WebSocket handshake: Unexpected response code: 301

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!

like image 349
Tobias Gassmann Avatar asked Aug 11 '18 17:08

Tobias Gassmann


1 Answers

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
like image 108
LoolKovsky Avatar answered Sep 19 '22 11:09

LoolKovsky