Friday 20 August 2021

[Tips] How to use Cloudflare Free SSL for Socket.io Server

Free SSL is a very interesting feature of Cloudflare. Cloudflare SSL has full support for WebSocket protocol. However, if you are using the web in conjunction with a socket.io server on the same server, you may encounter problems with the ssl port. Because the default port for ssl is always 443 but it is already used by the web server.

There are many ways to handle this problem, here I will guide you in a very simple way. That's how to configure Socket.io SSL through a proxy using Apache or Nginx.


Prepare:

NodeJs SocketIO server is listen on port 8088

Webserver (Apache or Nginx) is listen on port 80 and 443

Step 1: SocketServer config

Configure NodeJs SocketIO server to run in long polling mode without ssl on a certain port, eg port 8088.

Eg:

var app = require('express')(); //npm install express
var http = require('http').createServer(app);
var socketServer = require('socket.io')(http, { //npm install socketio
cors: {
origin: "*",
methods: ["GET", "POST"]
},
  transports: ['polling']
});
http.listen(8088, () => {
console.log('listening on port 8088');
});

Configure socket.io client to use 'polling' mode

Eg:

var socket = io('https://subdomain.yourdomain.com', { });
socket.on('connect', function () {
console.log('connected');
});

Step 2: Configure virtualhost proxy for Socket Server

Configure virtual host proxy to forward port 80 from cloudflare to the actual port of our Socket Server (I listen on port 80 because I am using Cloudflare flexible ssl, if you use Cloudflare full ssl or full strict ssl then listen on port 443 like your other virtualhost)

Apache:

<VirtualHost *:80>
    ServerAdmin admin@yourdomain.com
    ProxyPreserveHost On
    ServerName subdomain.yourdomain.com
    ProxyPass / http://127.0.0.1:8088/
    ProxyPassReverse / http://127.0.0.1:8088/
</VirtualHost>

Nginx:

server {
    listen 80;
    server_name subdomain.yourdomain.com;
    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         http://127.0.0.1:8088;
    }
}

Done !

Remember to reload your web server 

Now your NodeJs Socket Server is working perfectly with free ssl from CLoudflare

 

0 nhận xét:

Post a Comment