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/defaultStep 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
proxy_pass: Specifies the protocol and address of the proxied server where traffic should be forwarded (your Node.js application).proxy_http_version 1.1: Instructs Nginx to use HTTP/1.1, which is necessary for WebSockets and keep-alive connections.proxy_set_header UpgradeandConnection: Required to support WebSocket connections, which are common in modern Node.js applications.proxy_set_header Host: Passes the original host header from the client to the Node.js application.proxy_set_header X-Forwarded-For: Passes the actual IP address of the client to your Node.js application for logging and tracking.
Step 3: Test and Restart Nginx
Before applying the changes, test the Nginx configuration file for any syntax errors:
sudo nginx -tIf 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 nginxYour 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.