nginxrustwebsocketactix-web

Deploying actix Application with nginx


I created actix web & websocket within single application, and it works fine in localhost. Basically, after passing a login page, it opens a dashboard and a common Javascript's WebSocket.

new WebSocket(`ws://server:8181/client?token=${TokenString}`);

And it works fine. I don't want to expose this 8181 port on my production server, so my plan is using a sub path /ws to map to 8181 port.

So my /etc/nginx/sites-enabled/default config is:

server {

       server_name my_domain.com; # managed by Certbot

        ....
        #WebSocket part is here, under /ws path and mapped to 8181 port
        location /ws {
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header Host $host;
           proxy_set_header X-NginX-Proxy false;
           proxy_pass http://127.0.0.1:8181;
           proxy_redirect off;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection "upgrade";
        }

        #Here is my web app, / mapped to 8080 port
        location / {
            client_max_body_size 50m;
            client_body_buffer_size 50m;
            proxy_pass http://127.0.0.1:8080;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }

        location ^~ /\. {
           deny all;
        }

        #configs generated by Certbot
        listen [::]:443 ssl ipv6only=on; # managed by Certbot
        listen 443 ssl;
        #...
}

#redirect http to https
server {
    if ($host = my_domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


        listen 80 ;
        listen [::]:80 ;
    server_name my_domain.com;
    return 404; # managed by Certbot


}

My web page https://my_domain.com, works fine. But my mapped WebSocket connection doesn't.

new WebSocket(`wss://my_domain.com/ws/client?token=${TokenString}`);

With just WebSocket connection to ... failed: message, and /var/log/nginx/error.log shows nothing. Is something wrong with my nginx config?

*Edit: it turns out showing 404 in /var/log/nginx/access.log 😪


Solution

  • It turns out, the /ws path should be URL rewritten since my websocket didn't map /ws to anything. The idea was from here

    So my configuration is:

    location ~* ^/ws/ {
               rewrite ^/ws/(.*) /$1 break;
    ....