RajDev
RajDev

Reputation: 170

How to redirect NGINX to a websocket

  1. NGINX - sitting on 10.10.10.1
  2. LAMP - sitting on 172.168.1.1 , has phpwebsockets.This listens on http://172.168.1.1:8080 and having ws folder at http://172.168.1.1:8080/ws

Nginx supposed to forward request in this fashion.

 NGINX                                 --->      LAMP Websocket

http://10.10.10.1/randomstring/ --> https://10.10.10.1/randomstring/ --> http://172.168.1.1:8080

Currect /conf.d/internal.conf nginx config file is

server {
    listen         80;
    server_name    172.168.1.1;
    return         301 https://$host$request_uri; #redirect to self with https
    }
server {
    listen          443 ssl;
    server_name     172.168.1.1;
    root           /var/www/nginx/;
    index          index.html;
    proxy_cache one;
    location /ws {
        proxy_pass http://172.168.1.1:8080;
        # this magic is needed for WebSocket
        proxy_http_version  1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    location / {
        proxy_pass http://172.168.1.1:8080;
    }
}

I am unable to forward to /randomstring , it works for without 'randomstring'.

Upvotes: 2

Views: 6803

Answers (2)

Zexelon
Zexelon

Reputation: 494

One more thing to add, depending on how the back end websocket handler works you may need to add the following in the location block:

location /ws/ { # <-- note the trailing "/" nginx really really wants this always
        proxy_pass http://172.168.1.1:8080/; # <-- same here
        proxy_redirect http:// $scheme://;
        # ^-- the deep magic required to obtain the blessing of 
        # Ciscus, the greek god of networking. 
        # It forces nginx to rewrite the uri scheme from http to ws
        # before sending it over to the back end server. 

        # this magic is needed for WebSocket
        proxy_http_version  1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
    }

Upvotes: 0

Leet Hudka
Leet Hudka

Reputation: 226

Please add "/" at the end of proxy_pass

proxy_pass http://172.168.1.1:8080/;

Upvotes: 0

Related Questions