Hamza Janzaib avatar
AboutResumeProjectsWorkBlogContact
Home/Blog/AWS, Deployment & DevOps/Configuring Nginx as a Reverse Proxy for Node.js Applications

Configuring Nginx as a Reverse Proxy for Node.js Applications

Proxy headers, WebSocket upgrades, compression and timeouts: an Nginx config you can reason about.

By Hamza JanzaibNovember 28, 202612 min readIntermediate
Paste it into ChatGPT, Claude or any AI assistant.
  • nginx
  • node.js
  • reverse-proxy
  • devops
On this page · 14 sections
  • The request path
  • A minimal working configuration
  • Make the app trust the proxy
  • Use an upstream with keep-alive
  • Support WebSockets
  • Add HTTPS and redirect HTTP
  • Compression, body size and timeouts
  • Serve static assets directly
  • Rate limiting and basic hardening
  • Troubleshooting 502 Bad Gateway
  • Testing the configuration
  • Production considerations
  • Best practices
  • Conclusion

Running Node.js directly on port 80 or 443 works on a laptop and causes problems in production: you need root privileges to bind low ports, TLS configuration lives inside your app, slow clients hold connections open, and a second app on the same server has nowhere to go. A reverse proxy solves all of this. Nginx is the common choice because it is fast, stable and well understood.

This guide builds a production-minded Nginx configuration for a Node.js app: proxy basics, forwarded headers, keep-alive connections, WebSockets, compression, timeouts, rate limiting, security headers and the usual causes of 502 errors.

The request path

  1. 1Client

    HTTPS on port 443

  2. 2Nginx

    TLS, compression, rate limits, headers

  3. 3Node.js upstream

    HTTP on 127.0.0.1:3000

Nginx is the public front door; Node.js only listens on localhost

A minimal working configuration

Place it in /etc/nginx/sites-available/my-app and enable it with a symlink into sites-enabled:

nginx
server {    listen 80;    server_name app.example.com;    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;    }}

What each piece does:

  • proxy_pass sends requests to your app.
  • proxy_http_version 1.1 is required for keep-alive upstream connections and WebSockets (the default is 1.0).
  • Host preserves the hostname the client used.
  • X-Real-IP / X-Forwarded-For carry the client's address.
  • X-Forwarded-Proto tells the app whether the original request was HTTP or HTTPS, which matters for redirects and secure cookies.

Always test before reloading:

bash
sudo ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled/sudo nginx -tsudo systemctl reload nginx

Make the app trust the proxy

Your framework needs to know a proxy is in front of it, or it will log Nginx's address and think every request is plain HTTP:

ts
// Expressapp.set("trust proxy", 1); // trust one hop (Nginx)

Only trust as many hops as you actually have. Trusting arbitrary forwarded headers lets clients spoof their IP address.

Use an upstream with keep-alive

Opening a new TCP connection to Node for every request wastes time. An upstream block with keepalive reuses connections and lets you add more app instances later:

nginx
upstream app_backend {    server 127.0.0.1:3000;    # server 127.0.0.1:3001;   # add instances here for load balancing    keepalive 32;}server {    listen 80;    server_name app.example.com;    location / {        proxy_pass http://app_backend;        proxy_http_version 1.1;        proxy_set_header Connection "";   # required for upstream keep-alive        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;    }}

Support WebSockets

WebSocket connections start as an HTTP request with an Upgrade header. Nginx must pass it through, and it must pick the right Connection value for both normal and upgrade requests. A map in the http context does this:

nginx
# in nginx.conf, inside the http { } block (or a file included there)map $http_upgrade $connection_upgrade {    default upgrade;    ''      close;}
nginx
location /socket.io/ {    proxy_pass http://app_backend;    proxy_http_version 1.1;    proxy_set_header Upgrade    $http_upgrade;    proxy_set_header Connection $connection_upgrade;    proxy_set_header Host       $host;    proxy_read_timeout 3600s;   # keep idle sockets open longer}

Without a raised proxy_read_timeout, Nginx closes idle connections after 60 seconds by default, which looks like random disconnects.

Add HTTPS and redirect HTTP

Certificates from Let's Encrypt are free. The Certbot Nginx plugin edits your config and installs renewal:

bash
sudo certbot --nginx -d app.example.comsudo certbot renew --dry-run

The resulting setup looks like this (Certbot writes the certificate lines for you):

nginx
server {    listen 80;    server_name app.example.com;    return 301 https://$host$request_uri;}server {    listen 443 ssl;    http2 on;    server_name app.example.com;    ssl_certificate     /etc/letsencrypt/live/app.example.com/fullchain.pem;    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;    # ... proxy configuration as above ...}

Compression, body size and timeouts

nginx
server {    # ...    client_max_body_size 10m;      # reject larger uploads early (413)    gzip on;    gzip_comp_level 5;    gzip_min_length 1024;    gzip_types text/plain text/css application/json application/javascript image/svg+xml;    location / {        proxy_pass http://app_backend;        # ...        proxy_connect_timeout 5s;        proxy_send_timeout    30s;        proxy_read_timeout    30s;    }}

Tune timeouts to your slowest legitimate request. Very long timeouts hide hung upstreams and tie up connections.

Compress in one place only. If Node already compresses responses, disable one side to avoid double work.

Serve static assets directly

Nginx is far more efficient than Node at serving files. If your build produces static assets, serve them from disk with long cache headers and let only dynamic requests reach Node:

nginx
location /assets/ {    root /var/www/my-app/public;    expires 1y;    add_header Cache-Control "public, immutable";    access_log off;}

Rate limiting and basic hardening

Limit abusive request rates before they reach your app:

nginx
# http { } contextlimit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;# server/location contextlocation /api/ {    limit_req zone=api_limit burst=20 nodelay;    limit_req_status 429;    proxy_pass http://app_backend;}

Add a few safe defaults:

nginx
server_tokens off;   # do not advertise the Nginx versionadd_header X-Content-Type-Options "nosniff" always;add_header X-Frame-Options "DENY" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Only add HSTS when you are certain every subdomain you list will work over HTTPS. Rate limits at Nginx complement, not replace, application-level limits for authenticated routes.

Troubleshooting 502 Bad Gateway

502 means Nginx reached a problem talking to the upstream. Work through it in order:

  1. Is the app running? pm2 status or systemctl status my-app.
  2. Is it on the expected port? ss -tlnp | grep 3000. If the app binds to a different port, or only to a Unix socket, proxy_pass will fail.
  3. Does it answer locally? curl -i http://127.0.0.1:3000/health.
  4. What does Nginx say? sudo tail -n 50 /var/log/nginx/error.log usually names the exact problem (connect() failed, upstream timed out, upstream prematurely closed connection).
  5. Is the app crashing mid-request? Check the application logs.
  6. Is something blocking the connection? On systems with SELinux, setsebool -P httpd_can_network_connect 1 may be required.

Other common status codes:

StatusUsual cause
504 Gateway TimeoutUpstream too slow; raise proxy_read_timeout only after finding why
413 Request Entity Too LargeUpload exceeds client_max_body_size
400 Bad Request with large headers/cookiesIncrease large_client_header_buffers
Redirect loopsApp thinks the request is HTTP; forward X-Forwarded-Proto and trust the proxy
Wrong client IP in logsMissing forwarded headers or trust proxy

Testing the configuration

bash
sudo nginx -t                                   # syntax checkcurl -I http://app.example.com                  # expect a 301 to HTTPScurl -I https://app.example.com/health          # expect 200curl -sI -H "Accept-Encoding: gzip" https://app.example.com/ | grep -i content-encodingcurl -s -o /dev/null -w "%{http_code} %{time_total}s\n" https://app.example.com/

For WebSockets, connect with a client and confirm the connection stays open past 60 seconds.

Production considerations

Keep logs rotating (logrotate is configured by default for Nginx packages), monitor 5xx rates, reload rather than restart for config changes, store configuration in version control, and apply security updates regularly. When traffic grows, consider enabling proxy_cache for cacheable responses, or put a CDN in front of Nginx.

Best practices

  • Run nginx -t before every reload.
  • Forward Host, X-Forwarded-For and X-Forwarded-Proto, and trust the proxy in your app.
  • Use upstream with keepalive and proxy_http_version 1.1.
  • Keep Node bound to localhost so only Nginx is public.
  • Serve static files from Nginx, compress once, and set explicit timeouts.

Conclusion

An Nginx reverse proxy turns a Node.js process into a production service: it owns the public ports and TLS, shields the app from slow clients and abuse, and gives you a clean place to add caching, compression and load balancing. Start with the minimal block, add the forwarded headers, then layer on the pieces your application actually needs.

Frequently asked questions

+−Why put Nginx in front of Node.js?

Nginx terminates TLS, serves on ports 80 and 443 without running Node as root, buffers slow clients, compresses responses, applies rate limits, serves static files efficiently and lets several apps share one server.

+−Why do I get 502 Bad Gateway?

Nginx could not get a valid response from the upstream. The app is not running, it listens on a different port or interface than proxy_pass points to, it crashed during the request, or SELinux/firewall rules block the connection. Check the Nginx error log first.

+−How do I proxy WebSockets through Nginx?

Use HTTP/1.1 and forward the Upgrade and Connection headers, typically with a map block that sets Connection to upgrade when an Upgrade header is present. Also raise proxy_read_timeout so idle connections are not closed.

+−Why does my app see Nginx's IP instead of the client's?

Because the request comes from the proxy. Forward the client address with X-Forwarded-For and X-Real-IP, and tell your framework to trust the proxy (for Express, app.set('trust proxy', 1)).

+−What does proxy_set_header Host $host do?

It passes the original Host header to the application. Without it, Nginx sends the upstream's address, which breaks apps that generate absolute URLs or route by hostname.

+−How do I reload Nginx without dropping connections?

Run nginx -t to validate the configuration, then reload with systemctl reload nginx. A reload starts new workers with the new configuration and lets old workers finish existing requests.

+−Should Nginx or Node handle gzip compression?

Prefer Nginx. It is efficient at compression and keeps CPU work out of your Node process. Avoid compressing twice.

Further reading

  • nginx.org/en/docs/

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

AWS, Deployment & DevOpsNovember 28, 202618 min readIntermediate

Deploying a Node.js Application on AWS EC2 From Scratch

The full path from an empty EC2 instance to a Node.js app behind Nginx and HTTPS, with troubleshooting.

AWS, Deployment & DevOpsNovember 28, 202613 min readIntermediate

Solving AWS EC2 Deployment Problems: Ports, Nginx, SSL and Environment Variables

Symptom-first troubleshooting for EC2: timeouts, 502s, failed certificates and missing environment variables.

AWS, Deployment & DevOpsNovember 28, 202614 min readIntermediate

Building a CI/CD Pipeline for Automatic Deployment

Test, build and deploy on merge with GitHub Actions, using OIDC instead of long-lived keys where possible.

Built by Hamza Janzaib

PrivacyTerms