Nginx – How to forward non-http requests on port 80 to another port

nginxport-forwardingstream

There is an nginx web server listening to both 80 and 443 ports. I would like to process all the http requests as usual and forward all the non-http requests to another port (say, 1234).

My question is very similar to one already answered on stackoverflow: Is it possible to forward NON-http connecting request to some other port in nginx?. Perhaps, I misunderstand the most up-voted answer, but when I add something like this to nginx.conf:

stream {
    upstream backend {
        server example.com:1234;
    }

    server {
        listen 80;
        proxy_pass backend;
    }
}

I get the (expected) bind() to 0.0.0.0:80 failed (98: Address already in use) error.

Best Answer

nginx can only provide one kind of a service to a port at the same time.

So, this configuration will work:

http {
    server {
        listen 80;

        server_name example.com;
        ...
    }
}

stream {
    server {
        listen 81;
        proxy_pass backend;
    }

    upstream backend {
        server 127.0.0.1:12345;
    }
}

You cannot use the same port on stream and http blocks, since nginx has no way of distinguishing the traffic type.