Nginx Reverse Proxy Builder · Node.js / Express

Nginx Reverse Proxy Config for Node.js Express & PM2 (trust proxy & SSL)

Generate an Nginx reverse proxy server block for Node.js / Express with URL prefix rewrite previews, Certbot SSL redirects, WebSocket upgrade headers, and Docker DNS checks.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Domain, Routing & Upstream

2. TLS, WebSockets & Directives

# /etc/nginx/sites-available/api.nodeapp.dev.conf
# Generated by OpsCheck DevTools — Validate with: sudo nginx -t && sudo systemctl reload nginx

server {
    listen 80;
    listen [::]:80;
    server_name api.nodeapp.dev;

    # Redirect all plaintext HTTP traffic permanently to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name api.nodeapp.dev;

    # Let's Encrypt Certbot TLS Certificates
    ssl_certificate     /etc/letsencrypt/live/api.nodeapp.dev/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.nodeapp.dev/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    client_max_body_size 10M;

    # Gzip compression for JSON, JS, CSS, and SVG responses
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;

    # Baseline HTTP Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location /api/ {
        proxy_pass http://127.0.0.1:4000;
        proxy_http_version 1.1;
        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_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_set_header Connection "";

        proxy_connect_timeout 15s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
$sudo nginx -t && sudo systemctl reload nginx
URL Routing TransformationPrefix Preserved
GET https://api.nodeapp.dev/api/usershttp://127.0.0.1:4000/api/users

Strip Prefix OFF: Nginx preserves the full URI so upstream receives '/api/users'.

Configuration Diagnostics

  • infoPrefix Preserved (/api/ Forwarded Intact)

    GET https://api.nodeapp.dev/api/users -> Upstream receives http://127.0.0.1:4000/api/users. Strip Prefix OFF: Nginx preserves the full URI so upstream receives '/api/users'.

  • infoSingle-Layer CORS Policy Reminder

    This configuration intentionally omits Access-Control-Allow-Origin headers so your upstream backend framework (Laravel, FastAPI, Express, ASP.NET Core) owns CORS cleanly without duplicate header rejections.

Runs locally in your browser. Domain names and upstream topology are never sent to a server.

Common Nginx Error Log Pattern (Node.js / Express)

When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for Node.js / Express, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:

/var/log/nginx/error.log

2026/11/22 17:12:03 [error] 4112#4112: *773 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.19, server: api.nodeapp.dev, request: "POST /api/auth/login HTTP/2.0", upstream: "http://127.0.0.1:4000/api/auth/login", host: "api.nodeapp.dev"

Reverse Proxy Architecture & Header Forwarding for Node.js / Express

Running a Node.js Express API managed by PM2 on port 4000 behind Nginx is one of the most reliable, battle-tested production topologies on Linux servers. Nginx handles TLS termination, HTTP/2, static asset delivery, and slow-loris protection so Node.js's single-threaded event loop remains dedicated to business logic and database queries.

However, putting Nginx in front of Express changes how Express perceives every incoming HTTP request. Without explicit trust proxy configuration in Express and matching X-Forwarded-For / X-Forwarded-Proto headers in Nginx, req.ip always resolves to 127.0.0.1, req.secure returns false, and express-rate-limit ends up rate-limiting every visitor on Earth inside a single shared 127.0.0.1 bucket.

Likewise, Express session cookies with cookie: { secure: true } silently fail to set if Express believes the connection is insecure HTTP. Pairing app.set("trust proxy", 1) in Express with Nginx's proxy_set_header X-Forwarded-Proto $scheme and proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ensures accurate client IP attribution, valid secure cookies, and zero-downtime PM2 cluster reloads.

Finally, pay close attention to trailing slashes in proxy_pass when mounting Express under /api/. Leaving Strip Prefix OFF preserves /api/auth/login for Express routers mounted at app.use("/api", apiRouter), whereas turning Strip Prefix ON rewrites /api/auth/login to /auth/login before Express ever sees the request.

To harden an Express and PM2 production node behind Nginx, combine Nginx limit_req_zone rate limiting at the edge (stopping abusive floods before they touch Node.js) with Express trust proxy hop validation inside your application routes. Ensure systemd or pm2 startup persists your PM2 process list across kernel reboots, verify that Nginx passes X-Real-IP and X-Forwarded-For cleanly without stripping existing proxy headers inconsistently, and inspect /var/log/nginx/error.log after every deployment to confirm zero upstream connection refusals.

Step-by-Step Nginx & Node.js / Express Deployment Guide

Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.

  1. 1Enable trust proxy in Express for Accurate Client IPs and Secure Cookies

    src/server.ts

    Set app.set("trust proxy", 1) when exactly one Nginx proxy sits in front of Express (use 2 if Cloudflare CDN also proxies traffic to Nginx). Avoid trust proxy: true blindly, which lets express-rate-limit warn about spoofable X-Forwarded-For chains.

    src/server.tstypescript
    import express from 'express';
    import rateLimit from 'express-rate-limit';
    
    const app = express();
    
    // Trust the single local Nginx reverse proxy hop
    app.set('trust proxy', 1);
    
    app.use(
      '/api/',
      rateLimit({
        windowMs: 15 * 60 * 1000,
        max: 100,
        standardHeaders: true,
        legacyHeaders: false,
      })
    );
    
    app.get('/api/whoami', (req, res) => {
      res.json({
        clientIp: req.ip,
        protocol: req.protocol,
        secure: req.secure,
      });
    });
    
    app.listen(4000, '127.0.0.1');
  2. 2Run Express in PM2 Cluster Mode for Zero-Downtime Reloads

    ecosystem.config.cjs

    PM2 cluster mode spins up one Node.js worker per CPU core and shares port 4000 cleanly so pm2 reload reloads your API without Nginx returning 502 Bad Gateway during deploys.

    ecosystem.config.cjsjavascript
    module.exports = {
      apps: [
        {
          name: 'express-api',
          script: 'dist/server.js',
          instances: 'max',
          exec_mode: 'cluster',
          env_production: {
            NODE_ENV: 'production',
            PORT: 4000,
          },
        },
      ],
    };
  3. 3Synchronize Express Body Parsers With Nginx client_max_body_size

    src/middleware/bodyLimits.ts

    Express defaults to 100 KB for express.json() while Nginx defaults to 1 MB. Match both limits (e.g., 10 MB for JSON/uploads) so large payloads fail predictably rather than abruptly dropping connections.

    src/middleware/bodyLimits.tstypescript
    import express from 'express';
    
    export function registerBodyParsers(app: express.Express) {
      app.use(express.json({ limit: '10mb' }));
      app.use(express.urlencoded({ extended: true, limit: '10mb' }));
    }
  4. 4Validate Nginx Syntax, Reload, and Test Forwarded Headers

    terminal

    Reload Nginx after copying the generated config and call /api/whoami over HTTPS to confirm req.ip reflects your real public IP and req.secure equals true.

    terminalbash
    sudo nginx -t && sudo systemctl reload nginx
    curl -s https://api.nodeapp.dev/api/whoami

Common Node.js / Express Nginx Reverse Proxy Pitfalls

Review these three production failure modes before reloading Nginx on staging or live servers.

Pitfall 1

Using app.set("trust proxy", true) Breaking express-rate-limit v7+

Modern express-rate-limit raises ERR_ERL_PERMISSIVE_TRUST_PROXY if you pass boolean true to trust proxy because attackers could forge arbitrary X-Forwarded-For headers. Always specify the exact proxy hop count like app.set("trust proxy", 1) or "loopback".

Pitfall 2

502 Bad Gateway Caused by Binding Express to IPv6 Only While Nginx Proxies IPv4

Calling app.listen(4000) without a host argument can bind :: on some Linux kernels while Nginx proxies to 127.0.0.1:4000 (or vice versa when using localhost). Explicitly pass app.listen(4000, "127.0.0.1") and match 127.0.0.1:4000 in Nginx.

Pitfall 3

Enabling Express compression() Middleware Alongside Nginx gzip on

Compressing responses inside Node.js wastes event-loop CPU cycles and interferes with Nginx gzip heuristics. Let Nginx handle gzip compression and remove the Express compression middleware.

Related Tools

Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:

Frequently Asked Questions

Why does Nginx log "connect() failed (111: Connection refused)" for my Express API?
Error 111 means nothing is actively listening on 127.0.0.1:4000. Verify your PM2 process is online (pm2 status), check pm2 logs for startup crashes, and confirm Express is bound to port 4000 on 127.0.0.1.
Should I use Strip Prefix ON or OFF when proxying /api/ to Express?
Keep Strip Prefix OFF if your Express routes already include the prefix (app.use("/api", router)). Turn Strip Prefix ON if your Express app registers routes at the root (app.get("/users")) while Nginx exposes them publicly at /api/users.
How do I prevent 502 errors while deploying a new Express build with PM2?
Run Express in PM2 cluster mode with at least 2 instances and use pm2 reload express-api instead of pm2 restart. PM2 spins up new workers and waits for them to listen before gracefully draining old connections.
How many proxies should I trust if Cloudflare sits in front of Nginx and Express?
If traffic travels Client -> Cloudflare -> Nginx -> Express, set app.set("trust proxy", 2) in Express (or configure Nginx ngx_http_realip_module with Cloudflare IP ranges and keep trust proxy at 1).
Browse all 10 Nginx guides →