Configure Nginx as a Reverse Proxy for Node.js

This article provides a step-by-step guide on how to configure Nginx as a reverse proxy to route external web traffic to a Node.js application. You will learn how to set up the Nginx server block, configure the proxy pass directives, pass essential client headers, and test the configuration to ensure seamless and secure traffic routing.

Prerequisites

Before starting, ensure you have: * A Node.js application running on a local port (for example, http://localhost:3000). * Nginx installed on your server. * A domain name pointing to your server’s IP address (optional, but recommended).


Step 1: Open the Nginx Configuration File

Nginx configuration files for website blocks are typically located in the /etc/nginx/sites-available/ directory. You can edit the default configuration file or create a new one for your domain.

Run the following command to edit the default configuration file using the nano text editor:

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

Step 2: Configure the Server Block

Replace the existing content in the location / block, or create a new server block with the configuration below. Replace yourdomain.com with your actual domain name or server IP, and change 3000 to the port your Node.js app is running on.

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.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;
        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;
    }
}

Key Directives Explained


Step 3: Test and Restart Nginx

Before applying the changes, test the Nginx configuration file for any syntax errors:

sudo nginx -t

If the test is successful, you will see a message confirming that the syntax is okay and the test is successful.

Restart Nginx to apply the new configuration:

sudo systemctl restart nginx

Your Node.js application is now accessible through Nginx via port 80 (or your domain name). Nginx will handle all incoming traffic and safely route it to your background Node.js process.