nginx + pm2 locations error

quite new to nginx and struggle to make the simplest thing running on digitalocean ubuntu 16.04 server. I have a node.js app running behind pm2 and this works fine with requests to mydomain.com:5002/endpoint. However, I can’t get it working on a separate location like /app, constantly getting 404.
here’s the /etc/nginx/sites-available/default :

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;
        server_name mydomain.com;
        location /app/ {
                proxy_pass http://localhost:5002;
        }

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }



        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php7.0-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php7.0-fpm:
        #       fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}

Answer

If you have your pm2 running on example.com:5002/endpoint than your location block needs to state:

location /app {
proxy_pass http://localhost:5002/endpoint;
}

and you should be able to access your nodejs app on URL: http://example.com/app

for further reference you can refer to: https://devtidbits.com/2015/12/08/nginx-as-a-reverse-proxy-to-apache-tomcat/ it deals with the same setup only the port is different.

Attribution
Source : Link , Question Author : Дмитро Булах , Answer Author : Roman Spiak

Leave a Comment