Search code examples
nginxherokuproxyload-balancingproxypass

nginx upstream proxy_pass not working for heroku?


The below nginx config is working fine if I hardcode my herokuapp(backend API) in proxy_pass section:

http { 
    server {
        listen 8080;
        
        location / {
            proxy_pass http://my-app.herokuapp.com;
        }
    }
}

events { }

However if I try to add this in the upstream directive, its going to 404 page. I want to add this in upstream directive because I have other herokuapps as well where I want to load balance my requests.

This is the config which is not working:

http { 

    upstream backend {
        server my-app.herokuapp.com;
    }

    server {
        listen 8080;
        
        location / {
            proxy_pass http://backend;
        }
    }
}

events { }

These are all the things I tried after checking other SO answers:

  • add Host header while proxy passing. proxy_set_header Host $host;
  • add an extra slash at the end of backend.
  • In upstream directive, add server my-app.herokuapp.com:80 instead of just server my-app.herokuapp.com
  • In upstream directive, add server my-app.herokuapp.com:443 instead of just server my-app.herokuapp.com. This gives timeout probably because heroku doesn't allow 443(or maybe I didn't configure it).

Solution

  • Found the Issue: I was adding the wrong host. For heroku, for some reason you need to add host header with value as exactly what your app name is.

    If your herokuapp name is my-app.herokuapp.com, then you need to add this line for sure:

    proxy_set_header Host my-app.herokuapp.com;
    

    Full working config below:

    http { 
    
        upstream backend {
            server my-app.herokuapp.com;
        }
    
        server {
            listen 8080;
            
            location / {
                proxy_pass http://backend;
                proxy_set_header Host my-app.herokuapp.com;
            }
        }
    }
    
    events { }