Nginx WebSocket proxying keep getting HTTP 301 redirects Nginx WebSocket proxying keep getting HTTP 301 redirects curl curl

Nginx WebSocket proxying keep getting HTTP 301 redirects


In my case, it came from the client using path /websocket instead of /websocket/ thereby preventing the location rule to kick in.But the impact of locations order was a good hint!


As it turns out, the root location stanza in my Nginx configuration has been interfering with the WebSocket proxy pass tunnel. There are three ways to solve this problem.

  1. Modify the root location stanza to match exactly.

    location = / {    root   html;    index  index.html index.htm;}
  2. Re-order the root location stanza to be after the websocket location stanza (specific ones first, general ones last, just like how rewrite matching rule works).

  3. Removing the following root location stanza in the Nginx configuration will make it work.

    location / {    root   html;    index  index.html index.htm;}


Pay attention to your headers. In the header sent by web browsers and clients, it is Upgrade not upgrade.

change this:

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

to

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

Note the capital Upgrade