Introduction
You have a backend application listening on localhost:3000 and you need to put it behind Nginx with HTTPS and basic abuse protection. This guide walks through the full configuration: installing Nginx and Certbot, writing the reverse proxy block, adding zone-based rate limiting, obtaining a TLS certificate, and hardening the setup. Every config block is copy-pasteable. Every command assumes Debian 12 (Bookworm) or Ubuntu 22.04/24.04. Adapt package manager commands for RHEL/Fedora if needed.
Prerequisites
Before starting, confirm you have:
- A server with a public IP address and DNS A record pointing your domain (e.g.,
app.example.com) to that IP. - SSH access with a user that has
sudoprivileges. - Ports 80 and 443 open in your firewall (iptables, nftables, or cloud security group).
- The backend application already running and reachable at
127.0.0.1:3000(or whichever port you use).
Verify DNS resolution from another machine before proceeding. Certbot’s HTTP-01 challenge will fail if the domain does not resolve to your server’s public IP. A quick check:
dig +short app.example.comThe output should match your server’s public IPv4 address. If you see nothing or the wrong IP, fix your DNS records first. Certbot errors caused by DNS misconfiguration are the single most common failure in this entire process.
Installing Nginx and Certbot
On Debian/Ubuntu, install both packages from the default repositories:
sudo apt updatesudo apt install -y nginx certbot python3-certbot-nginxThe python3-certbot-nginx plugin lets Certbot modify your Nginx config automatically when obtaining and renewing certificates. You can also run Certbot in standalone mode (it spins up its own temporary web server on port 80), but the Nginx plugin is less disruptive because it does not require stopping Nginx during renewal.
After installation, confirm Nginx is running:
sudo systemctl status nginxYou should see active (running). If the service failed to start, check whether another process is already bound to port 80:
sudo ss -tlnp | grep ':80'Apache, Caddy, or a stale Nginx process are the usual culprits. Stop or remove the conflicting service before continuing.
The Base Reverse Proxy Configuration
Create a new server block file. Keeping one file per domain under sites-available with a symlink in sites-enabled is the conventional Debian/Ubuntu layout:
sudo nano /etc/nginx/sites-available/app.example.comPaste the following minimal reverse proxy config. This version handles HTTP only; TLS comes in a later step after Certbot runs:
server { listen 80; 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;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }}A few notes on the headers:
X-Real-IP and X-Forwarded-For pass the client’s actual IP to your backend. Without these, your application logs will show 127.0.0.1 for every request. X-Forwarded-Proto tells the backend whether the original request was HTTP or HTTPS, which matters for redirect logic and secure cookie flags. The Upgrade and Connection headers enable WebSocket proxying. If your app does not use WebSockets, these two lines are harmless but unnecessary.
Enable the site and test the config:
sudo ln -s /etc/nginx/sites-available/app.example.com /etc/nginx/sites-enabled/sudo nginx -tIf nginx -t prints syntax is ok and test is successful, reload:
sudo systemctl reload nginxAt this point, visiting http://app.example.com in a browser should show your backend application’s response. If you get a 502 Bad Gateway, Nginx reached the backend address but the backend refused the connection or is not running. If you get a 404, the server_name did not match the Host header in the request, so check your DNS and the server_name directive.
Removing the Default Site
Debian/Ubuntu ships a default server block that catches all unmatched requests. If your domain’s server block is not matching, the default site may be intercepting traffic:
sudo rm /etc/nginx/sites-enabled/defaultsudo systemctl reload nginxThis removes only the symlink, not the original file in sites-available.
Adding Rate Limiting
Nginx rate limiting uses the limit_req module, which is compiled in by default. The mechanism has two parts: a shared memory zone that tracks request counts per key (usually the client IP), and a directive in the location block that enforces the limit.
Defining the Rate Limit Zone
Add the zone definition in the http block. The cleanest place is a dedicated file:
sudo nano /etc/nginx/conf.d/rate-limit.conflimit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;Breaking this down:
$binary_remote_addruses the client IP in binary form (16 bytes for IPv6, 4 bytes for IPv4) as the key. This is more memory-efficient than$remote_addr.zone=api_limit:10mallocates 10 MB of shared memory for tracking. One megabyte holds roughly 16,000 IPv4 addresses or 8,000 IPv6 addresses. 10 MB handles around 160,000 unique IPs, which is sufficient for most applications.rate=10r/sallows 10 requests per second per IP. Nginx actually tracks this as 1 request per 100 ms internally.
Applying the Limit
Back in your server block file (/etc/nginx/sites-available/app.example.com), add the limit_req directive inside the location block:
location / { limit_req zone=api_limit burst=20 nodelay; limit_req_status 429;
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 Upgrade $http_upgrade; proxy_set_header Connection "upgrade";}The burst=20 parameter allows a client to exceed the base rate by up to 20 extra requests, which are queued and processed at the base rate. The nodelay modifier changes this behavior: instead of queuing the burst requests, Nginx forwards them immediately but still counts them against the burst budget. Once the burst budget is exhausted, excess requests get rejected.
Without nodelay, a client sending 20 requests at once would wait up to 2 seconds (20 requests at 10r/s) for them to drip through. With nodelay, all 20 go through instantly, but request 21 within the same window gets a 429.
limit_req_status 429 overrides the default 503 status code. Returning 429 (Too Many Requests) is semantically correct and lets clients distinguish rate limiting from a server error.
Choosing the Right Rate
10 requests per second per IP is a reasonable starting point for an API or web application. For a login endpoint, you want something much stricter. You can define multiple zones and apply different limits to different locations:
# In /etc/nginx/conf.d/rate-limit.conflimit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;limit_req_zone $binary_remote_addr zone=login_limit:5m rate=1r/s;# In the server blocklocation /api/login { limit_req zone=login_limit burst=5 nodelay; limit_req_status 429;
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;}
location / { limit_req zone=api_limit burst=20 nodelay; limit_req_status 429;
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;}Order matters: Nginx matches the most specific location first, so /api/login takes priority over /.
Rate Limiting Behind a Load Balancer or CDN
If Nginx sits behind a load balancer (AWS ALB, Cloudflare, etc.), $binary_remote_addr will be the load balancer’s IP, not the client’s. Every request looks like it comes from the same address, and your rate limit breaks.
In that case, use the real client IP from a trusted header:
# Extract real IP from X-Forwarded-Forset_real_ip_from 10.0.0.0/8; # your LB's CIDRset_real_ip_from 172.16.0.0/12;set_real_ip_from 192.168.0.0/16;real_ip_header X-Forwarded-For;real_ip_recursive on;Place this in the server block or in http context. The set_real_ip_from directives tell Nginx which source addresses are trusted proxies. real_ip_recursive on walks the X-Forwarded-For chain and picks the last untrusted address as the real client IP.
After this, $binary_remote_addr reflects the actual client, and rate limiting works correctly.
Test and reload after every change:
sudo nginx -t && sudo systemctl reload nginxObtaining a TLS Certificate with Certbot
With the HTTP server block in place and DNS resolving correctly, run Certbot:
sudo certbot --nginx -d app.example.comCertbot will:
- Verify domain ownership via the HTTP-01 challenge (it places a file under
/.well-known/acme-challenge/and Let’s Encrypt’s servers fetch it). - Obtain the certificate and key, storing them under
/etc/letsencrypt/live/app.example.com/. - Modify your Nginx server block to add
listen 443 ssl, thessl_certificateandssl_certificate_keydirectives, and an HTTP-to-HTTPS redirect block.
After Certbot finishes, your config file will look something like this (Certbot adds comments marking its managed lines):
server { listen 443 ssl; listen [::]:443 ssl; 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; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
location / { limit_req zone=api_limit burst=20 nodelay; limit_req_status 429;
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 Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }}
server { listen 80; listen [::]:80; server_name app.example.com;
if ($host = app.example.com) { return 301 https://$host$request_uri; }
return 404;}The file Certbot includes (/etc/letsencrypt/options-ssl-nginx.conf) sets reasonable TLS defaults: TLS 1.2 and 1.3 only, a curated cipher suite, OCSP stapling preferences. You can inspect it:
cat /etc/letsencrypt/options-ssl-nginx.confAutomatic Renewal
Certbot installs a systemd timer (or cron job, depending on the package) that runs certbot renew twice daily. Verify it exists:
sudo systemctl list-timers | grep certbotYou should see certbot.timer scheduled. Test renewal in dry-run mode:
sudo certbot renew --dry-runIf this succeeds, renewal will work automatically when certificates approach their 30-day expiration window (Let’s Encrypt certificates are valid for 90 days).
A common renewal failure: if you later change the Nginx config and break the server_name match or block access to /.well-known/acme-challenge/, renewal silently fails until the certificate expires. Set a calendar reminder to check sudo certbot certificates quarterly, or monitor certificate expiry with an external tool.
Hardening the TLS Configuration
Certbot’s defaults are decent, but you can tighten them. Add these directives inside the server block listening on 443:
# HSTS: tell browsers to always use HTTPS for this domainadd_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# Prevent MIME type sniffingadd_header X-Content-Type-Options "nosniff" always;
# Clickjacking protectionadd_header X-Frame-Options "SAMEORIGIN" always;
# TLS session caching for performancessl_session_cache shared:SSL:10m;ssl_session_timeout 1d;ssl_session_tickets off;
# OCSP staplingssl_stapling on;ssl_stapling_verify on;resolver 1.1.1.1 8.8.8.8 valid=300s;resolver_timeout 5s;A note on HSTS: the preload flag signals that you intend to submit your domain to browser preload lists. Once your domain is on those lists, browsers will refuse to connect over HTTP even if the HSTS header is absent. Only add preload if you are certain the domain will always use HTTPS. Removing a domain from preload lists takes months.
ssl_session_tickets off disables TLS session tickets, which have had forward secrecy issues in older implementations. With TLS 1.3, session tickets work differently and are generally safe, but disabling them is a conservative choice that has minimal performance impact when ssl_session_cache is enabled.
The resolver directive is required for OCSP stapling. Nginx needs to reach an OCSP responder, and it uses these DNS servers to resolve the responder’s hostname. Use whatever public DNS you trust.
After adding these headers, test with:
sudo nginx -t && sudo systemctl reload nginxThen verify your TLS setup externally:
curl -I https://app.example.comCheck for the Strict-Transport-Security, X-Content-Type-Options, and X-Frame-Options headers in the response.
For a thorough audit, use the SSL Labs test at https://www.ssllabs.com/ssltest/analyze.html?d=app.example.com. With the configuration above, you should score an A or A+.
Proxy Timeouts and Buffer Tuning
The default Nginx proxy timeouts are 60 seconds for connect, read, and send. If your backend has endpoints that take longer (report generation, file processing), you need to increase these:
location / { proxy_connect_timeout 10s; proxy_send_timeout 60s; proxy_read_timeout 90s;
proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 8k; proxy_busy_buffers_size 16k;
limit_req zone=api_limit burst=20 nodelay; limit_req_status 429;
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 Upgrade $http_upgrade; proxy_set_header Connection "upgrade";}proxy_connect_timeout 10s is how long Nginx waits to establish a TCP connection to the backend. If your backend is on localhost, this should complete in under a millisecond. A 10-second timeout catches the case where the backend process is dead and the connection hangs in the kernel’s SYN queue.
proxy_read_timeout 90s is the maximum time between two successive read operations from the backend. For a long-running request, the backend must send at least one byte every 90 seconds or Nginx closes the connection and returns 504.
Proxy buffering deserves attention. When proxy_buffering is on (the default), Nginx reads the entire response from the backend into memory (or disk, for large responses) before sending it to the client. This frees the backend connection quickly. If you disable buffering (proxy_buffering off), Nginx streams the response byte-by-byte, which ties up the backend connection for the duration of the client’s download. Disable buffering only for Server-Sent Events or streaming endpoints:
location /api/events { proxy_buffering off; proxy_cache off; proxy_read_timeout 3600s;
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 Connection "";}Logging and Monitoring Rate-Limited Requests
By default, rate-limited requests log at the error level with a message like:
2026/11/19 14:32:01 [error] 1234#1234: *5678 limiting requests, excess: 20.450 by zone "api_limit", client: 203.0.113.42, server: app.example.com, request: "GET /api/data HTTP/1.1", host: "app.example.com"You can reduce the log noise by setting a log level specifically for rate limiting:
limit_req_log_level warn;Place this in the http block or inside the server block. Setting it to warn instead of error keeps the messages but at a lower severity, which is useful if your log aggregator filters on severity.
For structured monitoring, create a custom log format that includes the request status and upstream response time:
log_format proxy_log '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' 'rt=$request_time urt=$upstream_response_time';
access_log /var/log/nginx/app.example.com.access.log proxy_log;Add the log_format in the http block (e.g., in /etc/nginx/nginx.conf) and the access_log directive in your server block. The $upstream_response_time field shows how long the backend took to respond, which helps you distinguish slow backends from slow clients.
To count 429 responses over time, a quick grep works:
grep '" 429 ' /var/log/nginx/app.example.com.access.log | wc -lFor production monitoring, feed these logs into Prometheus (via nginx-prometheus-exporter or mtail), Grafana Loki, or the ELK stack.
The Complete Configuration File
Here is the full, consolidated server block after all the steps above:
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;limit_req_zone $binary_remote_addr zone=login_limit:5m rate=1r/s;server { listen 443 ssl; listen [::]:443 ssl; 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; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d; ssl_session_tickets off;
ssl_stapling on; ssl_stapling_verify on; resolver 1.1.1.1 8.8.8.8 valid=300s; resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "SAMEORIGIN" always;
limit_req_log_level warn;
access_log /var/log/nginx/app.example.com.access.log proxy_log; error_log /var/log/nginx/app.example.com.error.log warn;
location /api/login { limit_req zone=login_limit burst=5 nodelay; limit_req_status 429;
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; }
location / { limit_req zone=api_limit burst=20 nodelay; limit_req_status 429;
proxy_connect_timeout 10s; proxy_send_timeout 60s; proxy_read_timeout 90s;
proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 8k; proxy_busy_buffers_size 16k;
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 Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }}
server { listen 80; listen [::]:80; server_name app.example.com;
if ($host = app.example.com) { return 301 https://$host$request_uri; }
return 404;}Testing the Setup
Verify HTTPS
curl -v https://app.example.com/ 2>&1 | head -30Look for SSL connection using TLSv1.3 (or TLSv1.2) and a 200 status code. If you see certificate errors, check that the ssl_certificate path points to fullchain.pem (which includes the intermediate CA), not just cert.pem.
Verify Rate Limiting
Use ab (Apache Bench) or a simple loop to send a burst of requests:
for i in $(seq 1 30); do curl -s -o /dev/null -w "%{http_code}\n" https://app.example.com/doneWith rate=10r/s and burst=20, the first 20-ish requests should return 200. After the burst budget is exhausted, subsequent requests within the same second should return 429. The exact boundary depends on timing between requests.
For a more precise test, ab sends requests concurrently:
ab -n 50 -c 10 https://app.example.com/Check the output for non-2xx responses. Those are the rate-limited ones.
Verify HTTP-to-HTTPS Redirect
curl -I http://app.example.com/Expected output includes:
HTTP/1.1 301 Moved PermanentlyLocation: https://app.example.com/Verify Security Headers
curl -sI https://app.example.com/ | grep -iE '(strict-transport|x-content-type|x-frame)'Expected:
strict-transport-security: max-age=63072000; includeSubDomains; preloadx-content-type-options: nosniffx-frame-options: SAMEORIGINTroubleshooting
502 Bad Gateway
The error log will contain a line like:
connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.42, server: app.example.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/"This means Nginx successfully received the client request but could not connect to the backend. Causes:
- The backend application is not running. Check with
sudo ss -tlnp | grep 3000. - The backend is listening on a different address (e.g.,
0.0.0.0:3000vs127.0.0.1:3000). Match theproxy_passaddress to whatever the backend binds. - A firewall rule on the server blocks localhost connections (rare, but check
sudo iptables -L -n).
504 Gateway Timeout
upstream timed out (110: Connection timed out) while reading response header from upstreamThe backend accepted the connection but did not respond within proxy_read_timeout. Either the backend is overloaded, the endpoint is genuinely slow, or the backend is deadlocked. Increase proxy_read_timeout for specific slow endpoints, or investigate the backend’s performance.
Certbot Fails with “Connection Refused” or “Timeout”
Failed authorization procedure. app.example.com (http-01): urn:ietf:params:acme:error:connection :: The server could not connect to the client to verify the domainLet’s Encrypt’s validation servers could not reach port 80 on your server. Common causes:
- A firewall or security group blocks inbound port 80. Cloud providers (AWS, GCP, Azure) require explicit security group rules.
- Your DNS A record points to the wrong IP.
- Your ISP or hosting provider blocks port 80 (some residential ISPs do this).
Verify reachability from outside your network:
# From a different machinecurl -v http://YOUR_SERVER_IP/.well-known/acme-challenge/testIf this times out, the problem is network-level, not Nginx.
Certbot Renewal Fails Silently
Check the renewal log:
sudo cat /var/log/letsencrypt/letsencrypt.log | tail -50Common issue: you added a location /.well-known block that overrides Certbot’s access. Make sure no deny all or return directive intercepts /.well-known/acme-challenge/. If you have a catch-all location / that requires authentication, add an exception:
location /.well-known/acme-challenge/ { root /var/www/html; allow all;}Rate Limiting Not Working
If all requests pass through without any 429 responses, check:
- The
limit_req_zonedirective is in thehttpcontext, not inside aserverblock. Placing it insideservercauses a config error. - The zone name in
limit_reqmatches the zone name inlimit_req_zone. A typo means Nginx rejects the config atnginx -t. - If behind a proxy/CDN,
$binary_remote_addrmay be the CDN’s IP. See the “Rate Limiting Behind a Load Balancer” section above.
”Too Many Certificates” Error from Let’s Encrypt
Let’s Encrypt enforces rate limits: 50 certificates per registered domain per week. If you are testing repeatedly, use the staging environment:
sudo certbot --nginx --staging -d app.example.comStaging certificates are not trusted by browsers, but the issuance limits are much higher. Once your configuration works, remove the staging certificate and run Certbot without --staging.
Permission Denied on Certificate Files
If Nginx logs:
cannot load certificate "/etc/letsencrypt/live/app.example.com/fullchain.pem": BIO_new_file() failed (SSL: error:02001002:system library:fopen:No such file or directory)The symlinks under /etc/letsencrypt/live/ point to files in /etc/letsencrypt/archive/, which is readable only by root. Nginx’s master process runs as root and can read these files. If you changed Nginx to run the master process as a non-root user, you need to adjust permissions:
sudo chmod 750 /etc/letsencrypt/archive/sudo chmod 750 /etc/letsencrypt/live/Do not make certificate private keys world-readable.
Connection Limiting as a Complement to Rate Limiting
Rate limiting controls requests per second. Connection limiting controls simultaneous open connections per IP. The two work well together. A slow-loris attack, for example, opens many connections and sends data very slowly, which does not trigger rate limits but exhausts worker connections.
Add a connection zone:
# In /etc/nginx/conf.d/rate-limit.conflimit_conn_zone $binary_remote_addr zone=addr_conn:10m;Apply it in the server block:
server { limit_conn addr_conn 20; limit_conn_status 429;
# ... rest of config}This allows a maximum of 20 simultaneous connections per client IP. Adjust based on your application’s profile. A single-page app that opens multiple parallel API requests might legitimately use 6 to 10 connections. A normal website browsing session rarely exceeds 6.
Performance Considerations
Worker Processes and Connections
Check your Nginx worker configuration in /etc/nginx/nginx.conf:
worker_processes auto;events { worker_connections 1024;}worker_processes auto sets one worker per CPU core. worker_connections 1024 means each worker can handle 1024 simultaneous connections. Total capacity is worker_processes * worker_connections. For a reverse proxy, each client connection uses two file descriptors (one for the client, one for the upstream), so effective capacity is half the worker_connections value.
On a 4-core server with the defaults, you can handle roughly 2048 simultaneous proxied connections. For higher traffic, increase worker_connections to 4096 or higher. Also raise the OS file descriptor limit:
# Check current limitulimit -n
# Set in /etc/security/limits.conf* soft nofile 65536* hard nofile 65536And in the Nginx systemd unit override:
sudo systemctl edit nginx[Service]LimitNOFILE=65536Keepalive to Upstream
By default, Nginx opens a new TCP connection to the backend for every request. For high-throughput setups, this creates unnecessary overhead. Enable keepalive connections to the upstream:
upstream backend { server 127.0.0.1:3000; keepalive 32;}
server { # ... location / { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Connection ""; # ... other headers }}The keepalive 32 directive maintains a pool of up to 32 idle keepalive connections to the backend per worker process. The Connection "" header clears the Connection: close default, allowing HTTP/1.1 persistent connections to the upstream.
This change requires using an upstream block instead of a bare address in proxy_pass. The trade-off is a slightly more complex config for reduced TCP handshake overhead.
Multiple Backend Servers (Load Balancing)
If you have more than one backend instance, the upstream block supports round-robin (default), least connections, and IP hash:
upstream backend { least_conn; server 127.0.0.1:3000; server 127.0.0.1:3001; keepalive 32;}least_conn sends each new request to the backend with the fewest active connections. This works better than round-robin when request processing times vary. ip_hash pins each client IP to a specific backend, which provides session affinity but uneven load distribution.
Health checks in open-source Nginx are passive: if a backend returns errors, Nginx marks it as unavailable for a configurable period. Active health checks (periodic probes to a health endpoint) require Nginx Plus or a third-party module like nginx_upstream_check_module.
Passive health check parameters:
upstream backend { server 127.0.0.1:3000 max_fails=3 fail_timeout=30s; server 127.0.0.1:3001 max_fails=3 fail_timeout=30s; keepalive 32;}After 3 failed requests within 30 seconds, Nginx stops sending traffic to that backend for 30 seconds, then tries again.
Restricting Access by IP (Allowlisting)
For admin endpoints or internal APIs, restrict access to specific IP ranges:
location /admin { allow 10.0.0.0/8; allow 192.168.1.0/24; allow 203.0.113.50; deny all;
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;}Nginx evaluates allow and deny directives in order. The first match wins. Requests from IPs not in the allow list get a 403 Forbidden.
If you are behind a proxy and using set_real_ip_from (as described in the rate limiting section), the allow/deny directives use the restored real client IP, not the proxy’s IP.
Serving Static Files Directly
If your backend serves static assets (CSS, JS, images) from a known directory, Nginx can serve them directly without proxying to the backend. This reduces backend load and improves response times:
location /static/ { alias /var/www/app/static/; expires 30d; add_header Cache-Control "public, immutable"; access_log off;}alias maps the URL path to a filesystem path. expires 30d sets the Expires and Cache-Control: max-age headers. access_log off reduces log volume for static assets. The immutable cache directive tells browsers that the file will never change at this URL, which eliminates revalidation requests. Only use immutable if your asset URLs include a content hash or version number (e.g., app.a1b2c3.js).
Maintenance and Rotation
Log Rotation
Nginx logs grow indefinitely without rotation. Debian/Ubuntu install a logrotate config at /etc/logrotate.d/nginx by default. Verify it exists and covers your custom log paths:
cat /etc/logrotate.d/nginxIf your custom access_log path is not under /var/log/nginx/, add it to the logrotate config or create a new file:
/var/log/nginx/app.example.com.*.log { daily missingok rotate 14 compress delaycompress notifempty sharedscripts postrotate [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid) endscript}The kill -USR1 signal tells Nginx to reopen its log files after rotation.
Keeping Nginx and Certbot Updated
Subscribe to the Nginx security mailing list or monitor CVE databases. On Debian/Ubuntu, unattended-upgrades can handle security updates automatically:
sudo apt install unattended-upgradessudo dpkg-reconfigure unattended-upgradesCertbot updates through the package manager. If you installed Certbot via snap instead of apt, updates happen automatically.
Testing Config Changes Safely
Always run nginx -t before reloading. A syntax error in the config will prevent Nginx from reloading, but it will keep running with the old config. A more dangerous mistake is a semantically valid but logically wrong config (e.g., removing the proxy_pass directive). For critical production servers, keep a backup of the working config:
sudo cp /etc/nginx/sites-available/app.example.com /etc/nginx/sites-available/app.example.com.bakAfter editing, test and reload:
sudo nginx -t && sudo systemctl reload nginxIf the reload introduces issues, restore the backup:
sudo cp /etc/nginx/sites-available/app.example.com.bak /etc/nginx/sites-available/app.example.comsudo systemctl reload nginxSummary of Trade-offs
Rate limiting at the Nginx level is effective against casual abuse and simple bots, but it is not a substitute for application-level rate limiting. Nginx cannot distinguish between authenticated users, API keys, or request types beyond what the URL path reveals. If you need per-user or per-API-key rate limits, implement them in your application and use Nginx rate limiting as a coarse outer layer.
TLS termination at Nginx adds a small amount of CPU overhead for the handshake and encryption. On modern hardware with AES-NI instructions, this overhead is negligible for most workloads. If you are processing thousands of new TLS connections per second, consider enabling TLS session resumption (which the config above does via ssl_session_cache) and using ECDSA certificates (smaller, faster) instead of RSA.
The Nginx plugin for Certbot modifies your config files in place, which can create merge conflicts if you also edit them manually. If you prefer full control over your config, use Certbot in certonly mode with the webroot or standalone authenticator, and manage the ssl_certificate directives yourself:
sudo certbot certonly --webroot -w /var/www/html -d app.example.comThis obtains the certificate without touching your Nginx config. You then add the ssl_certificate and ssl_certificate_key lines manually.
The configuration in this guide covers the most common reverse proxy scenario: a single domain, one or more backend instances on localhost, HTTPS with auto-renewing certificates, and per-IP rate limiting. For more complex setups involving multiple domains, wildcard certificates, or mutual TLS (mTLS), the core concepts remain the same but the config grows accordingly.