Web Sockets reverse proxy support in Nginx

If you use Socket.IO or Faye with WebSockets, and at the same time want to use reverse proxies with Nginx, then you will encounter the problem of supporting WebSocket in Nginx. It simply does not exist - WebSocket uses HTTP 1.1, while Nginx can correctly proxy only HTTP 1.0.

What to do?

You can try to bypass - use HAProxy to proxy tcp connections, or slip into using Long-polling.
But there is a way to implement reverse proxying with NGINX, using an unofficial patch that implements the tcp_proxy module in nginx, which will make it possible to forward arbitrary tcp connections (essentially the same as that provided by HAProxy).

Compiling nginx with the tcp_proxy module

... in general terms, it will look like this: The code is given taking into account that you have installed the building tools and satisfied all nginx dependencies. For example, I note that for owners of ubuntu-server it makes sense instead of make install to do a checkinstall to install nginx as a package, as well as add the necessary options for additional modules and paths to the logs and configuration, for example, as described in Q&A .

export NGINX_VERSION=1.0.4
curl -O nginx.org/download/nginx-$NGINX_VERSION.tar.gz
git clone github.com/yaoweibin/nginx_tcp_proxy_module.git
tar -xvzf nginx-$NGINX_VERSION.tar.gz
patch -p1 < ../nginx_tcp_proxy_module/tcp.patch
./configure --add-module=../nginx_tcp_proxy_module/
sudo make && make install

sudo apt-get install curl build-essential git-core
sudo apt-get build-dep nginx

Proxy configuration

Let's create a simple vhost for the case when we want to forward port 80 to ports 8001, 8002, 8003, 8004 of our backends (which, for example, are node.js servers with faye or socket.io modules) with load balancing.

And on the 9000 port of the localhost, we will display debugging information on the status of the proxy. By running backends, we can observe a joyful picture: When implementing several backends, you need to understand that there are no guarantees that the client will always connect to the same backend (for example, the node.js server), therefore it is necessary to think over the correct ways to manage sessions in cluster (e.g. use redis). Good luck PS. Based on an article by Johnathan Leppert

tcp {
upstream websockets {
## node processes
check interval=3000 rise=2 fall=5 timeout=1000;
server {
server_name вашеИмяДомена;
tcp_nodelay on;
proxy_pass websockets;

http {
## status check page for websockets
server {
listen 9000;

location /websocket_status {


Also popular now: