I've got simple site served from node.js which sends messages to socket.io (it works on the same node.js instance). Everything works fine on localhost but the problem starts when I try to setup nginx on vps, the client cannot find my socket.io endpoint.
https://example.com - socket.io client
https://example.com/sender - socket.io server
Please keep in mind that clients from other domains also have to able to use the socket.io endpoint.
node app:
const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const port = 8080;
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept-Type');
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
app.listen(port, () => {
console.log("Server is running on port: " + port);
});
server.listen(4200);
app.get('/', (req, res) => {
res.render('index');
});
io.on('connection', (client) => {
console.log('Client connected...');
client.on('messages', (data) => {
client.emit('reply', data);
});
});
nginx configuration:
server {
listen 80;
listen [::]:80;
root /home/project_path/;
server_name example.com;
if ($scheme != "https") {
return 302 https://$host$request_uri;
} # managed by Certbot
location /sender {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://localhost:4200;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location / {
proxy_pass http://localhost:8080;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com-
0001/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com-
0001/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
}