mdashikjs/blog
All posts
Nginx as a Reverse Proxy for Node.js: The Production Config
DevOps

Nginx as a Reverse Proxy for Node.js: The Production Config

DevOps4 min

Nginx as a Reverse Proxy for Node.js: The Production Config

Node.js should not serve static files, terminate SSL, or handle rate limiting. That is Nginx's job. Here is the production config I copy into every new project.

NginxNode.jsDevOpsSecurity
Share:

The base config

upstream node_app {
  server 127.0.0.1:3000;
  keepalive 64;
}

server {
  listen 443 ssl http2;
  server_name api.example.com;

  ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_ciphers HIGH:!aNULL:!MD5;

  # Gzip compression
  gzip on;
  gzip_types application/json text/plain application/javascript;
  gzip_min_length 1024;

  # Security headers
  add_header X-Frame-Options DENY;
  add_header X-Content-Type-Options nosniff;
  add_header X-XSS-Protection "1; mode=block";
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

  # Proxy to Node.js
  location / {
    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_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_cache_bypass $http_upgrade;
  }

  # Static files — served by Nginx directly
  location /static/ {
    alias /var/www/app/public/;
    expires 30d;
    add_header Cache-Control "public, immutable";
  }
}

# Redirect HTTP to HTTPS
server {
  listen 80;
  server_name api.example.com;
  return 301 https://$server_name$request_uri;
}

Why keepalive matters

keepalive 64 reuses connections between Nginx and Node.js instead of opening a new TCP connection per request. Without it, connection overhead adds 1-3ms to every request. With 1,000 req/s, that is wasted time.

WebSocket support

The Upgrade and Connection headers in the proxy config enable WebSocket passthrough. Without them, WebSocket connections fail silently — the handshake starts over HTTP but never upgrades.

Rate limiting at the Nginx layer

limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;

location /api/ {
  limit_req zone=api burst=50 nodelay;
  proxy_pass http://node_app;
}

This is cheaper than rate limiting in Node.js. Nginx rejects the request before it even reaches your application.

The one thing people forget

proxy_set_header X-Forwarded-For. Without it, every request to your Node app appears to come from 127.0.0.1. Your logging, rate limiting, and geo-IP lookup all break.

MA

Written by Md Ashik

Senior Software Engineer building reliable backends. I write about the practical tradeoffs behind shipping software that holds up in production.