Nginx Reverse Proxy & SSL Hardening with Let’s Encrypt on Ubuntu 24.04

When moving a backend application from localhost to a public cloud VPS, exposing Node.js, Python, or Go servers directly to the internet on raw ports (like :3000 or :8000) is a major architectural and security hazard. Application runtimes are built to handle application logic, not to defend against slowloris attacks, terminate TLS handshakes at scale, or serve static assets efficiently.

In modern production environments, placing an Nginx reverse proxy in front of your containerized workloads or systemd services solves these problems. Nginx acts as the single, hardened gatekeeper: absorbing client connections, enforcing automated SSL/TLS encryption via Let’s Encrypt, caching responses, and passing clean, buffered HTTP requests to your upstream apps.

In this guide, we will walk through the complete, step-by-step production configuration of Nginx on Ubuntu 24.04 LTS (Noble Numbat). We will configure an upstream proxy pass for a Node.js or Docker service, automate free wildcard/domain SSL certificates with Certbot, implement rate limiting to block brute-force attacks, and apply A+ rated SSL security headers.

Table of Contents

1. Why Put Nginx in Front of Your Backend?

Before touching terminal commands, it is essential to understand the architectural separation of concerns between your application server and Nginx:

CapabilityDirect Node.js / Python RuntimeWith Nginx Reverse Proxy
SSL/TLS TerminationHigh CPU overhead; complex cert renewal inside app codeOffloaded entirely to C-optimized OpenSSL workers with automated renewal
DDoS & Rate LimitingConsumes Node.js single-thread event loopDrops malicious spikes in memory before reaching the backend
Port ManagementRequires non-root permission workarounds for ports 80/443Binds cleanly to 80/443; routes traffic to internal ports (3000, 8080)
Zero-Downtime ReloadsDropping connections during restartsNginx reloads upstream configs seamlessly without dropping active client TCP sockets
Static Asset DeliverySlow event-loop streaming for images and CSSDirect kernel-level sendfile() streaming at maximum disk throughput

2. Step 1: Installing and Verifying Nginx on Ubuntu 24.04

Ubuntu 24.04 LTS ships with modern Nginx packages in its default universe repositories. Start by refreshing your APT package lists and installing the core package:

# Update package index
sudo apt update && sudo apt upgrade -y

# Install Nginx
sudo apt install nginx -y

# Verify Nginx status and systemd enablement
sudo systemctl status nginx --no-pager

Ensure Nginx is set to start automatically whenever your VPS reboots:

sudo systemctl enable nginx

3. Step 2: Firewall Configuration with UFW

On any cloud server, an unconfigured firewall leaves database and application ports exposed. We will use UFW (Uncomplicated Firewall) to allow only SSH, HTTP, and HTTPS traffic while locking down all internal application ports:

# Allow OpenSSH first to prevent getting locked out of your server
sudo ufw allow OpenSSH

# Allow standard HTTP (80) and HTTPS (443) traffic for Nginx
sudo ufw allow 'Nginx Full'

# Enable the firewall
sudo ufw --force enable

# Check firewall status
sudo ufw status verbose

At this point, only ports 22, 80, and 443 can receive outside packets. Your backend app running on port 3000 will communicate strictly over local loopback (127.0.0.1), completely shielded from external port scans.

4. Step 3: Creating a Production Reverse Proxy Server Block

Never modify the default /etc/nginx/nginx.conf file directly for site-specific routing. Instead, create a dedicated virtual host configuration under /etc/nginx/sites-available/.

Assume your domain is api.example.com and your backend Node.js or Docker container is listening on port 3000. Create a new site config:

sudo nano /etc/nginx/sites-available/api.example.com

Paste the following production-ready reverse proxy configuration:

# Upstream block defines backend application pool
upstream backend_app {
    server 127.0.0.1:3000;
    keepalive 64; # Reuses TCP connections between Nginx and backend
}

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

    # Maximum allowed request body size (vital for file uploads)
    client_max_body_size 25M;

    location / {
        proxy_pass http://backend_app;
        proxy_http_version 1.1;

        # WebSockets and persistent connection headers
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';

        # Essential client identification headers
        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;

        # Timeouts to prevent slow client exhaustion
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # Buffer configuration for high throughput
        proxy_buffering on;
        proxy_buffer_size 128k;
        proxy_buffers 4 256k;
        proxy_busy_buffers_size 256k;
    }
}

Enable the site by symlinking it into sites-enabled, test the syntax, and reload Nginx:

# Symlink to sites-enabled
sudo ln -s /etc/nginx/sites-available/api.example.com /etc/nginx/sites-enabled/

# Test syntax (crucial before reloading in production)
sudo nginx -t

# Reload configuration seamlessly
sudo systemctl reload nginx

5. Step 4: Automated SSL/TLS Certificates with Certbot

With DNS pointing to your server’s public IP address, we will install the official Electronic Frontier Foundation (EFF) Certbot tool via Snap (the recommended package manager on Ubuntu for continuous certificate auto-renewals):

# Install Certbot via Snap
sudo snap install --classic certbot

# Ensure certbot command is globally linked
sudo ln -s /snap/bin/certbot /usr/bin/certbot

# Obtain and install certificate automatically for Nginx
sudo certbot --nginx -d api.example.com

Certbot will inspect your Nginx server block, complete the HTTP-01 challenge against Let’s Encrypt, issue a 2048-bit RSA certificate, and configure an automatic HTTP-to-HTTPS redirect.

Verify that the systemd auto-renewal timer is active:

# Test renewal dry-run
sudo certbot renew --dry-run

6. Step 5: Hardening SSL/TLS for an A+ Security Score

Default SSL configurations often permit legacy cryptographic ciphers or lack HTTP security headers. To achieve an A+ rating on SSL Labs Qualys Test, open your SSL site configuration and add these enterprise headers inside the server { ... } SSL block:

# Enforce modern TLS protocols only (deprecating TLS 1.0 and 1.1)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;

# Session caching for fast TLS handshakes
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;

# HTTP Strict Transport Security (HSTS) - Enforces HTTPS for 1 year
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

# Prevent clickjacking attacks
add_header X-Frame-Options "DENY" always;

# Prevent MIME type sniffing
add_header X-Content-Type-Options "nosniff" always;

# Referrer Policy for user privacy
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

# Permissions Policy (disables unnecessary hardware access)
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

7. Step 6: Rate Limiting & DDoS Protection

A common vulnerability of unprotected REST APIs is credential stuffing and denial of service. Nginx provides built-in leaky bucket rate limiting that protects your database without consuming application compute.

Open /etc/nginx/nginx.conf and define a shared memory rate-limiting zone inside the http { ... } block:

http {
    # 10MB shared memory zone tracking client IPs, allowing max 10 requests per second
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
    
    # Custom status code when rate limit is exceeded
    limit_req_status 429;
}

Then apply the rule to your sensitive API routes (like login or authentication endpoints) in your site block:

location /api/v1/auth/ {
    # Allow burst of 5 requests with nodelay for real users
    limit_req zone=api_limit burst=5 nodelay;
    proxy_pass http://backend_app;
}

8. Step 7: Gzip Compression & Buffer Tuning

Compressing JSON payloads and static responses dramatically lowers latency and bandwidth consumption on mobile networks. Add the following compression rules inside your /etc/nginx/nginx.conf:

gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6; # Optimal balance of CPU and compression ratio
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types
    text/plain
    text/css
    application/json
    application/javascript
    application/x-javascript
    text/xml
    application/xml
    application/xml+rss
    text/javascript;

Next Steps: Building Scalable Production Architectures

With your Nginx reverse proxy hardened, automated, and running on Ubuntu 24.04, your backend infrastructure is fully protected. Continue strengthening your deployment workflow with our companion tutorials:

9. Frequently Asked Questions (FAQ)

What is the difference between an upstream proxy and a forward proxy?

A forward proxy sits in front of client devices to inspect, filter, or anonymize outgoing internet traffic (e.g. corporate VPNs). A reverse proxy sits in front of web servers to inspect, balance, and encrypt incoming web requests from the internet before forwarding them to internal application services.

Why does Certbot fail with “Challenge failed for domain”?

This almost always indicates a DNS propagation delay or a firewall blocking port 80. Let’s Encrypt requires port 80 to be open to verify domain ownership via the HTTP-01 challenge. Ensure your domain’s A record matches your VPS IP address and that UFW allows ‘Nginx Full’.

Can Nginx handle WebSockets through proxy_pass?

Yes. By including proxy_set_header Upgrade $http_upgrade; and proxy_set_header Connection "upgrade"; in your location block, Nginx seamlessly upgrades the initial HTTP request to a persistent, bidirectional WebSocket connection without closing the TCP socket.

Written and verified by Mohit Kumar — Software Engineer and Founder of Tech Aventure. For questions or production server tuning advice, connect via our Contact Page.


Related Articles

Authoritative Reference: Consult the Official NGINX Documentation for normative standards and release specifications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top