2

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.

2 Answers2

1

As @AlexeyTen mentioned in his comment, sslh is the right tool for this purpose. It has built-in support for HTTP, SSL, SSH, OpenVPN, tinc and XMPP protocols and it supports custom regex tests as well.

For example, to make sslh forward http requests to nginx, and non-http requests to ejabberd, it's enough to replace in all nginx's virtual hosts

    listen 80;

with

    listen 127.0.0.1:88;

(it's also possible to use listen 127.0.0.1:80 if sslh with listen to port 80 on specific ip only, or to use e.g. listen 88), then install sslh and edit its default options:

RUN=yes
DAEMON_OPTS="--numeric --user sslh --listen 0.0.0.0:80 --http 127.0.0.1:88 --xmpp 127.0.0.1:5222 --pidfile /var/run/sslh/sslh.pid"

(/etc/default/sslh in debian). And, finally, just (re)start the services:

systemctl restart nginx
systemctl start sslh

If --transparent option for sslh is required, there would be some additional steps - they are well-documented on github.

0

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.

Tero Kilkanen
  • 38,887