Nginx Reverse Proxy Builder · Next.js / Node.js

Nginx Reverse Proxy Config for Next.js SSR (App Router, SSL & Streaming)

Generate an Nginx reverse proxy server block for Next.js / Node.js 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/app.example.com.conf
# Generated by OpsCheck DevTools — Validate with: sudo nginx -t && sudo systemctl reload nginx

# Required in http {} context (or top of sites-available file) for clean WebSocket upgrades
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    listen [::]:80;
    server_name app.example.com;

    # 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 app.example.com;

    # Let's Encrypt Certbot TLS Certificates
    ssl_certificate     /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/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 / {
        proxy_pass http://127.0.0.1:3000;
        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;

        # WebSocket & Upgrade support (requires map $http_upgrade $connection_upgrade)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_cache_bypass $http_upgrade;

        proxy_connect_timeout 15s;
        proxy_send_timeout 120s;
        proxy_read_timeout 120s;
    }
}
$sudo nginx -t && sudo systemctl reload nginx
URL Routing TransformationPrefix Preserved
GET https://app.example.com/usershttp://127.0.0.1:3000/users

Root location '/' forwards '/users' unchanged to upstream http://127.0.0.1:3000/users.

Configuration Diagnostics

  • infoRoot Proxy Path (/) Preserves Full Request URI

    GET https://app.example.com/users -> Upstream receives http://127.0.0.1:3000/users. Root location '/' forwards '/users' unchanged to upstream http://127.0.0.1:3000/users.

  • passWebSocket Upgrade & Extended Timeout (120s) Enabled

    Configured HTTP/1.1 Upgrade, Connection $connection_upgrade map, and extended proxy_read_timeout for persistent real-time sockets.

  • 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 (Next.js / Node.js)

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

/var/log/nginx/error.log

2026/11/22 14:22:18 [error] 1842#1842: *914 upstream prematurely closed connection while reading response header from upstream, client: 203.0.113.42, server: app.example.com, request: "GET /dashboard HTTP/2.0", upstream: "http://127.0.0.1:3000/dashboard", host: "app.example.com"

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

Self-hosting a Next.js App Router application behind Nginx on a Linux VPS or container host gives you predictable pricing and full infrastructure control, but Next.js expects specific HTTP/1.1 proxy behavior that default Nginx boilerplate omits. Your Next.js server listens on http://127.0.0.1:3000 (via next start, standalone output, or PM2), while Nginx terminates TLS on port 443, compresses responses, and forwards client identity headers so Server Actions and authentication callbacks construct accurate HTTPS URLs.

Next.js App Router relies heavily on React Server Components streaming, Suspense boundaries, and Route Handlers that stream AI completions or Server-Sent Events. By default, Nginx buffers upstream responses internally before flushing bytes to the browser, which stalls React Suspense streaming and makes incremental UI chunks appear all at once after the entire render finishes. Configuring clean HTTP/1.1 keepalives, appropriate proxy_read_timeout ceilings, and disabling proxy_buffering on streaming routes preserves sub-second Time to First Byte.

Equally important are static asset caching and Server Action origin verification. Because Next.js fingerprints every bundle inside /_next/static/* with content hashes, serving or caching that path with immutable 1-year Cache-Control headers removes massive load from Node.js. Meanwhile, Next.js 14/15+ validates the Origin header against Host and X-Forwarded-Host on every Server Action POST; if Nginx strips or alters Host or X-Forwarded-Proto, Server Actions fail immediately with HTTP 403 or "Invalid Server Actions request."

Before cutting over DNS for a self-hosted Next.js deployment, inspect both /var/log/nginx/error.log and your Next.js stdout logs while submitting a Server Action, navigating client-side routes, and loading a Suspense-streamed page. Confirming HTTP/2 TLS termination, intact X-Forwarded-Proto: https headers, and sufficient client_max_body_size for Server Action file uploads guarantees production parity with managed edge platforms.

For zero-downtime Next.js production rollouts behind Nginx, combine PM2 cluster reload or blue-green Docker deployments with explicit proxy_connect_timeout and proxy_next_upstream directives so brief Node.js restarts never surface raw 502 Bad Gateway pages to active users. Monitoring both Nginx access timing ($upstream_response_time) and Next.js server memory consumption helps catch uncached SSR bottlenecks early, while keeping /_next/static/ off the Node.js event loop lets a single modest VPS serve thousands of concurrent App Router visitors reliably.

Step-by-Step Nginx & Next.js / Node.js 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. 1Run Next.js Production Server Bound to Localhost Only

    ecosystem.config.cjs (PM2 / systemd)

    Bind next start to 127.0.0.1:3000 so port 3000 is never exposed directly to the public internet bypassing Nginx TLS and rate limits. Use output: "standalone" in next.config.ts for minimal memory footprints.

    ecosystem.config.cjs (PM2 / systemd)bash
    module.exports = {
      apps: [
        {
          name: 'nextjs-app',
          script: 'node_modules/next/dist/bin/next',
          args: 'start -H 127.0.0.1 -p 3000',
          env: {
            NODE_ENV: 'production',
            PORT: 3000,
          },
        },
      ],
    };
  2. 2Add Immutable Caching for /_next/static/ and Streaming Headers in Nginx

    /etc/nginx/sites-available/app.example.com.conf

    Add a dedicated location /_next/static/ block inside your HTTPS server block so content-hashed JS and CSS assets cache aggressively, and forward Host, X-Forwarded-Host, and X-Forwarded-Proto intact for Server Actions.

    /etc/nginx/sites-available/app.example.com.confnginx
    location /_next/static/ {
        proxy_pass http://127.0.0.1:3000;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }
    
    location /api/stream {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_cache off;
        proxy_read_timeout 300s;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
  3. 3Allow Server Action Body Size and Trusted Proxied Origins in Next.js

    next.config.ts

    Synchronize Next.js Server Action body limits with Nginx client_max_body_size (default 1 MB in both Nginx and Next.js) and configure allowedOrigins if reverse proxies rewrite hostnames.

    next.config.tstypescript
    import type { NextConfig } from 'next';
    
    const nextConfig: NextConfig = {
      output: 'standalone',
      experimental: {
        serverActions: {
          bodySizeLimit: '10mb',
          allowedOrigins: ['app.example.com'],
        },
      },
    };
    
    export default nextConfig;
  4. 4Enable the Site, Issue Certbot SSL, and Reload Nginx Safely

    terminal (Ubuntu / Debian)

    Symlink the configuration into sites-enabled, validate Nginx syntax before reloading, and provision auto-renewing Let's Encrypt certificates with Certbot.

    terminal (Ubuntu / Debian)bash
    sudo ln -s /etc/nginx/sites-available/app.example.com.conf /etc/nginx/sites-enabled/
    sudo certbot --nginx -d app.example.com
    sudo nginx -t && sudo systemctl reload nginx

Common Next.js / Node.js Nginx Reverse Proxy Pitfalls

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

Pitfall 1

Nginx proxy_buffering Stalling React Suspense and AI Streaming Routes

Nginx buffers upstream responses in 4KB–8KB chunks by default. On Next.js streaming Route Handlers or Server Components using Suspense, buffering holds the entire stream until completion unless you set proxy_buffering off; (or emit X-Accel-Buffering: no from Next.js).

Pitfall 2

Server Actions Failing With "x-forwarded-host header does not match origin"

Next.js compares the browser Origin header against Host and X-Forwarded-Host to stop CSRF attacks on Server Actions. If Nginx omits proxy_set_header Host $host; or sets X-Forwarded-Host to an internal upstream name like 127.0.0.1:3000, every Server Action POST fails.

Pitfall 3

Caching HTML Pages Alongside /_next/static/ Bundles

Applying long expires or proxy_cache directives to the root location / caches stale SSR HTML referencing deleted chunk hashes from previous deployments, causing ChunkLoadError crashes in user browsers. Only set immutable caching on /_next/static/.

Related Tools

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

Frequently Asked Questions

Do I need WebSocket Upgrade headers for Next.js in production behind Nginx?
Standard production Next.js SSR does not require WebSockets unless you attach a custom WebSocket server or real-time channel. However, keeping HTTP/1.1 Upgrade and Connection $connection_upgrade configured guarantees zero breakage for custom socket endpoints and staging HMR servers.
Why do Next.js image optimization requests (/_next/image) return 502 or 504 behind Nginx?
Next.js sharp image resizing fetches remote source images synchronously on first request. If remote fetches take longer than Nginx's default 60s timeout or if outbound DNS fails inside Docker, Nginx logs 504 Gateway Timeout. Raising proxy_read_timeout to 120s and verifying outbound container DNS resolves this.
Should I let Nginx or Next.js handle Gzip compression?
Handle Gzip (or Brotli) in Nginx and set compress: false inside next.config.ts. Offloading compression from the single-threaded Node.js event loop to Nginx's C-level workers reduces Node CPU usage and prevents double-compression overhead.
Why did my Next.js file upload return 413 Request Entity Too Large even after raising bodySizeLimit?
Both Nginx and Next.js enforce independent 1 MB defaults. Even if you raise serverActions.bodySizeLimit to 10mb in next.config.ts, Nginx rejects the request before it ever reaches Node.js unless client_max_body_size 10M; is set in your Nginx server block.
Browse all 10 Nginx guides →