How do I make my reverse proxied Nginx server access other routed files in an express app running on port 3000?

user16050654 asked:

Currently I have an express app inside /usr/share/nginx/myexpress

The express application is listening and working perfectly on port 3000. My NGINX server is reverse proxying to it and I can view the default express page by going to kodix.com.br.

The problem is, I can’t go to kodix.com.br/hello for example after routing it. I can only access it by going through the ip address. (Like this example but with other numbers: 143.94.233.176:3000/hello)

Here’s my current sites-available nginx configuration:

upstream node_app{
server 127.0.0.1:3000;
}

server {

    root /usr/share/nginx/myexpress;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name kodix.com.br www.kodix.com.br;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
        proxy_pass http://node_app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

}

How do I make it so I can access other express pages using my nginx server?

My answer:


The normal soluton to this is to use a named location. In this setup, nginx will serve static content first. If no static content exists for the URL path, instead of returning a 404, it is then passed to the named location, which sends it to your app.

It’s a very simple addition:

    location / {
        try_files $uri $uri/ @express;
    }

    location @express {
        proxy_pass http://node_app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

P.S. It is not a good idea to store your web files in /usr/share/nginx. This directory is owned by the package manager and it has the authority to delete everything in it whenever the nginx package is updated or removed. (It most likely will not do, but this is a risk that I would not take.)


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.