[solved] 502 Bad Gateway - NGINX, Shellinabox, subdomain

Posted October 18, 2018 41.1k views
NginxDNSLEMPLet's EncryptUbuntu 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
  • DNS entry for points to server with NGINX
  • NGINX is a reverse proxy for

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

server {

    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

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

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.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
3 answers

Great answer, helped me a lot! thank you for sharing

mauriciolazo28 thanks a lot