jayzee
jayzee

Reputation: 225

nginx re-route all data based on port (nginx proxy)

I'm still new to nginx and I want to accomplish this.

I have two servers (server1 and server2), with an sftp server (bitvise) on server1. And on server2 I have an nginx docker container running.

I want to configure nginx so when trafic comes to server2 (the one with nginx) on port 22 , it get redirected to server1, where my sftp sever is present.

I have an dns "transfer.test.com" mapped to my server2 public IP (tested).

This is the configuration I have added to nginx conf file.

server {
 listen 22;
 server_name transfer.test.com;
 return 301 https://google.com;


 location / {
   set $sftp server1-private-ip:22;
   proxy_pass  $sftp;
  }
} 

server1-private-ip is the private IP of server1 (the one with sftp).

but till now its not working. I can connect to sftp using filezile using the private IP of server1 BUT I can't connect to sftp using filezila using the private IP of server2, means the trafic is not getting redirected.

Thank you for the help.

Upvotes: 2

Views: 2371

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15470

If you want to use nginx as a proxy to non-HTTP protocols like SSH or SFTP, you should define your server in a stream context rather than http one. Typical main configuration file (usually /etc/nginx/nginx.conf) looks like

user              <username>;
worker_processes  <number>;
...

events {
    worker_connections  <number>;
}

http {
    include       /etc/nginx/mime.types;
    ... # other global http directives here
    include       /etc/nginx/conf.d/*.conf;
}

As you can see, configuration files for individual servers (or server groups) are being included within the http context. You should add stream block to your main configuration file:

user              <username>;
worker_processes  <number>;
...

events {
    worker_connections  <number>;
}

http {
    ...
}

stream {
    server {
        listen      22;
        proxy_pass  <server1_private_ip>:22;
    }
}

Directives like server_name or location are meaningless in the server blocks defined under the stream context. Please note that for using above configuration nginx should be compliled with ngx_stream_core_module and ngx_stream_proxy_module modules.

Upvotes: 6

Related Questions