# Nginx reverse proxy for multiple Node.js apps in subfolders

> Learn how to set up an nginx reverse proxy so multiple Node.js apps can run on different ports yet be served from subfolders under one domain.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-08-13 | Topics: [Networking](https://flaviocopes.com/tags/network/) | Canonical: https://flaviocopes.com/nginx-reverse-proxy/

I recently set up a VPS on DigitalOcean to run a few different [Node.js](https://flaviocopes.com/nodejs/) scripts under the same domain.

Now, you can't have two different Node.js apps listen on the same port, so you have to use a reverse proxy. Nginx is commonly used for that.

I built a free [nginx config generator](https://flaviocopes.com/tools/nginx-generator/) that writes these server blocks for you, including the reverse proxy setup shown below.

I set up each Node app to run on its own subfolder, so I had to edit the Nginx configuration:

```
sudo nano /etc/nginx/sites-available/default
```

which was this:

```
server {
        listen 80 default_server;
        listen [::]:80 default_server;
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
        server_name hellonode;

        location ^~ /assets/ {
                gzip_static on;
                expires 12h;
                add_header Cache-Control public;
        }

        location / {
                proxy_http_version 1.1;
                proxy_cache_bypass $http_upgrade;

                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;

                proxy_pass http://localhost:3000;
        }
}
```

This configuration allows one Node.js app, running on port 3000, to be the main app served on `/`.

I wanted to have an app running under `/myservice`, so I created a Node app listening on port 3001 and I added this configuration:

```
location /myservice {
        rewrite ^/myservice/(.*)$ /$1 break;

        proxy_http_version 1.1;
        proxy_cache_bypass $http_upgrade;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_pass http://localhost:3001;
}
```

I checked the configuration was fine using

```
sudo nginx -t
```

and I restarted nginx:

```
sudo systemctl restart nginx
```
