Nginx Reverse Proxy


title: Using Reverse proxy with nginx date: 2024-03-16 author: gitamgadtaula description: 'A demo on how to use nginx reverse proxy on a node server'

Using Reverse Proxy in Nginx

Reverse proxy is a technique used to route incoming requests from clients to backend servers. In the context of web servers, it allows you to forward requests to different applications or servers based on certain criteria, such as URL paths or hostnames. Nginx, a popular web server and reverse proxy server, provides robust support for configuring reverse proxy setups.

In this tutorial, we'll explore how to set up a reverse proxy in Nginx to forward requests to a Node.js server running on port 3000.

Prerequisites

Before getting started, ensure that you have Nginx installed on your system. You'll also need a Node.js application running on port 3000.

Setting Up Reverse Proxy

First, open your Nginx configuration file. This is typically located in /etc/nginx/nginx.conf or /etc/nginx/sites-available/default on Linux systems.

Add the following configuration block inside the server block:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:3000;
        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;
    }
}

Running two different applications on 80


http {
    # ... other configurations

    server {
        listen 80;  # Listen on port 80 (the public-facing port)
        server_name your_domain_name www.your_domain_name;  # Adjust domain names

        # Location block for application on port 8080
        location /app1 {
            proxy_pass http://localhost:8080;  # Forward requests to port 8080
            proxy_set_header Host $host;  # Preserve the original hostname
            proxy_set_header X-Real-IP $remote_addr;  # Optionally, for backend awareness
        }

        # Location block for application on port 8081
        location /app2 {
            proxy_pass http://localhost:8081;  # Forward requests to port 8081
            proxy_set_header Host $host;  # Preserve the original hostname
            proxy_set_header X-Real-IP $remote_addr;  # Optionally, for backend awareness
        }
    }
}

Test the Nginx configuration

sudo nginx -t

Restart Nginx

sudo systemctl restart nginx