[solved] 502 Bad Gateway - NGINX, Shellinabox, subdomain ssh.example.com

October 18, 2018 9.1k views
Nginx Let's Encrypt DNS LEMP Ubuntu 16.04

I just wanted to share the answer to an issue that has been giving me headaches for a couple of days.

I needed to have this setup:

  • Shell-in-a-box needs to be accessed at https://ssh.example.com
  • DNS entry for ssh.example.com points to server with NGINX
  • NGINX is a reverse proxy for example.com:4200

I configured Shell-in-a-box in the server, configured the DNS entry for ssh.example.com and also configured the server block for Nginx with the following setup:

server {
    server_name ssh.example.com;

    location / { 
        proxy_pass http://localhost:4200; 
        proxy_set_header Host      $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_read_timeout 350;
        proxy_connect_timeout 350;
    }

    location ~ /\.ht {
        deny all; 
    }

    #
    # HERE GOES ALL THE Let´s Encrypt auto configuration stuff.
    #
}

After that setup, I always got an 502 - Bad Gateway error. no matter what I did, additionally /var/log/nginx/error.log showed this every time I opened ssh.example.com

[error] 15177#15177: *6040 upstream prematurely closed connection while reading response header from upstream, client: 208.87.234.202, server: ssh.example.com

Finally understanding the log, what “upstream prematurely closed connection” means is that, nginx got the request, knows where to send it, it then sends it but the receiving application (Shell-in-a-box), closed the connection forcefully and prematurely. Hence, the problem lies in the application itself, right?

After a couple of days reading, I found the answer. Shell-in-a-box only receives requests in https protocol, but in the other hand, all examples of reverse proxy explicitly specify that http should be used to proxy the requests to the application.

So after changing proxy_pass http://localhost:4200; to proxy_pass https://localhost:4200; al worked beautifully.

1 Answer
Have another answer? Share your knowledge.