Skip to the content

Lesson 248 of 296

nginx as a reverse proxy

What you will learn

  • Forward proxy vs reverse proxy
  • What nginx does in front of an application
  • A complete reverse proxy configuration with HTTPS
  • Static files, compression, WebSockets and security headers
  • Load balancing with nginx
  • Testing and reloading safely
On this page

Proxies

  • A forward proxy acts for clients (a company proxy that employees' browsers go through).
  • A reverse proxy acts for servers: clients talk to it, and it passes requests to the application behind it.

nginx (pronounced "engine-x") is the most widely used reverse proxy and web server. Caddy, Traefik, HAProxy and cloud load balancers fill similar roles.

What nginx does in front of your app

  • TLS termination: handles HTTPS certificates; your Node app speaks plain HTTP on localhost.
  • Serves static files (built front-end assets) very efficiently.
  • Routing: /api to the Node app, everything else to the front end.
  • Compression (gzip or Brotli), caching, request size limits, timeouts.
  • Load balancing across several app instances.
  • Security: hides the app's port, adds security headers, rate limits.

A complete configuration

upstream api_backend {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    keepalive 32;
}

server {
    listen 80;
    server_name jobprep.example www.jobprep.example;
    return 301 https://jobprep.example$request_uri;
}

server {
    listen 443 ssl;
    http2 on;
    server_name jobprep.example;

    ssl_certificate     /etc/letsencrypt/live/jobprep.example/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/jobprep.example/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

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

    client_max_body_size 10m;
    gzip on;
    gzip_types text/css application/javascript application/json image/svg+xml;

    root /srv/jobprep/web/dist;

    location /assets/ {
        add_header Cache-Control "public, max-age=31536000, immutable";
        try_files $uri =404;
    }

    location /api/ {
        proxy_pass http://api_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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_read_timeout 30s;
    }

    location /ws/ {
        proxy_pass http://api_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_read_timeout 1h;
    }

    location / {
        try_files $uri $uri/ /index.html;
    }
}

What each part does:

  • upstream: a group of app servers; nginx load-balances between them (round robin by default; least_conn; for least connections). keepalive reuses connections to the app.
  • The port 80 server redirects everything to HTTPS with a 301.
  • ssl_certificate: certificates from Let's Encrypt, usually obtained and renewed automatically by certbot.
  • http2 on enables HTTP/2 (the directive form used by nginx 1.25.1 and later).
  • Security headers (HSTS and others, Lesson 264); always adds them to error responses too.
  • client_max_body_size: rejects bodies larger than 10 MB with 413.
  • /assets/: hashed build files cached for a year (Lesson 198). Do not also add expires 1y; here: testing this configuration showed that expires plus add_header Cache-Control sends two Cache-Control headers. Note also that an add_header inside a location replaces all add_header lines inherited from the server block, so a real config repeats the security headers in that location or uses an include file.
  • /api/: proxied to Node. proxy_pass http://api_backend; (no path after the name) keeps the full path, so /api/orders reaches the app as /api/orders; the app's routes must include /api. Writing proxy_pass http://api_backend/; (with a trailing slash) strips the /api/ prefix instead. Both were checked in testing; mixing them up is a common cause of 404s. The X-Forwarded-* headers tell the app the real client IP and that the original request was HTTPS. In Express, set app.set("trust proxy", 1) so req.ip and req.secure use them (only when you are really behind a proxy; otherwise clients could fake these headers).
  • /ws/: WebSocket upgrade headers (Lesson 205) and a long read timeout.
  • location / with try_files ... /index.html: a single-page app fallback, so refreshing /lessons/7 returns the app instead of 404.

Safe changes

sudo nginx -t                 test the configuration for errors
sudo systemctl reload nginx   apply it without dropping connections

Always test before reloading; a typo in a live config can take every site on the server down.

How to say it in an interview

"nginx is a reverse proxy in front of the application: it terminates TLS with Let's Encrypt certificates, redirects HTTP to HTTPS, serves static assets with long cache headers, compresses responses, limits body sizes, adds security headers, and proxies API and WebSocket traffic to one or more Node processes defined in an upstream block. It forwards the client IP and protocol in X-Forwarded headers, which the app trusts only when behind the proxy. For single-page apps I add a try_files fallback to index.html, and I always run nginx -t before a graceful reload."

Key words

WordMeaning
Reverse proxyA server that forwards client requests to back-end servers
TLS terminationDecrypting HTTPS at the proxy
Upstreamnginx's group of back-end servers
X-Forwarded-ForHeader carrying the original client IP
try_filesTries paths in order, with a fallback
certbot / Let's EncryptFree automated TLS certificates

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.