简体   繁体   中英

How to configure Nginx reverse proxy for web sockets?

I have ASP Core application running on Ubuntu.

In front of the application there is Nginx webserver used as a reverse proxy as follows:

    # Part 1 : Redirect http tp https
    server {
            server_name example.com www.example.com;
            listen 80;
            listen [::]:80;

            return 301 https://www.example.com$request_uri;
    }

    # Part 2 : Reverse proxy for https requests. Get the app response from localhost:5000
    server {
            listen 443 ssl;
            server_name example.com www.example.com;

            ssl_certificate     /home/aspuser/ssl/example.crt;
            ssl_certificate_key /home/aspuser/ssl/example.key;

            access_log /var/log/nginx/reverse-access.log;
            error_log /var/log/nginx/reverse-error.log;

            location / {
                        proxy_pass http://127.0.0.1:5000;
                    }
    }

    # Part 3 : Reverse proxy for websockets on port 3000. Get the app response from localhost:5000/ws
     server {
        listen 3000 ssl;
        server_name example.com www.example.com
        
        ssl_certificate     /home/aspuser/ssl/example.crt;
        ssl_certificate_key /home/aspuser/ssl/example.key;
            
        location / {
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header Host $host;

              proxy_pass http://127.0.0.1:5000/ws;

              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "upgrade";
            }    
      }

Part 1 & 2 are working properly. The apps shows with ssl certificate correctly.

Part 3: Websocket reverse proxy is not working. When I'm trying to send websocket message from Chrome Dev Tab using the following Javascript:

var socket = new WebSocket("wss://www.example.com:3000");

socket.onopen = function(e) {
  console.log("Connection established");
};

I'm getting the error:

WebSocket connection to 'wss://www.example.com:3000/' failed: Error in connection establishment: net::ERR_CONNECTION_RESET

The same application works properly from localhost (I'm getting websocket response on localhost) but not when published on Ubuntu. (The port 3000 is allowed in the server firewall).

Can anyone help please?

I believe your

proxy_pass http://127.0.0.1:5000/ws;

should read

proxy_pass http://127.0.0.1:5000/ws/;

I seem to remember that when the location ends in /, so should the forwarded path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM