How to properly configure nginx to listen port from express and websocket with HTTPS?

40 Views Asked by At

I have a domain on vps i will call it there example.com By entering https://example.com i should see index.html served by express and then client will connect on that same page/url to the websocket.

This is the main part of my server code:

const http = require("https");
const fs = require('fs');
const app = require("express")();
app.get("/", (req, res) => res.sendFile(__dirname + "/index.html"))

const hostname = 'localhost';
const options = {
    key: fs.readFileSync(__dirname + '/cert/example_com.key'),
    cert: fs.readFileSync(__dirname + '/cert/www_example_com.chained.crt'),
};

app.listen(3001, () => console.log("Listening on http port 3001"))
const websocketServer = require("websocket").server
const httpServer = http.createServer(options);

httpServer.listen(3000, () => console.log("Listening.. on 3000"))

//hashmap clients
const clients = {};
const games = {};
const wsServer = new websocketServer({
    "httpServer": httpServer
})
wsServer.on("request", request => {

this is part of connecting to this server in index.html

var socket = new WebSocket('wss://example.com');

I think the problem is in nginx configuration, i should have sth like

server {

    location / {
        proxy_pass https://example.com:3001;
    }

   location / {
        proxy_pass https://example.com:3000;
    }
}

I tried something like that but i doesnt worked.

this is my current nginx configuration which i use

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name example.com www.example.com;

    ssl_certificate /root/www_example_com.chained.crt;
    ssl_certificate_key /root/example_com.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    location / {
        proxy_pass https://example.com:3001;
        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;
    }
}

When i enter to https://example.com/ i get 502 Bad Gateway

I checked connection by console:

wscat -c wss://example.com:3000
Connected (press CTRL+C to quit)
curl https://example.com:3001
curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

Given server code worked on my local envirnoment but i dont know how to fix it on vps. Also when i used only websockets and doesnt had express and listening on that port, everything worked well, problem started when i wanted to add express.

0

There are 0 best solutions below