Nginx Reverse Proxy Explained: Rate Limiting and Security

Rate this post

Imagine you built a small Python web app on your laptop. It works great when you open http://localhost:8081. So you put it on a cloud server, point users straight to port 8081, and call it a day.

Within hours, bots start scanning your server, someone hits refresh 500 times a second, and your app crashes. Even worse, every response tells attackers the exact server software you are running.

This is why real-world DevOps engineers never let internet users talk directly to an application server. Instead, they put Nginx in front as a reverse proxy. In this guide, we will break down how Nginx works from zero—in plain English that any high-school student can follow—using real configs and real bugs we fixed on Ubuntu 24.04.

1. What Is a Reverse Proxy? (The School Gatekeeper Analogy)

Think of your Python app like a principal’s office inside a school. Students, parents, and random visitors do not walk straight into the principal’s office unannounced. They stop at the front gate first.

The security guard at the gate checks who is visiting, stops troublemakers from flooding the hallway, and only passes legitimate visitors inside. Nginx is that front-gate guard.

  • Your Python app listens only on 127.0.0.1:8081 (localhost). Nobody on the internet can reach port 8081 directly.
  • Nginx listens on 0.0.0.0:80 (the public web port), inspects every incoming request, applies safety rules, and quietly forwards valid requests to 127.0.0.1:8081.
Direct App vs Nginx Reverse Proxy Architecture Diagram
Without Nginx, bots hit your app directly. With Nginx, your Python app stays hidden on localhost (127.0.0.1:8081).

2. Installing Nginx and Checking Its Baseline

On Ubuntu 24.04, installing Nginx takes one command:

sudo apt-get update && sudo apt-get install -y nginx
nginx -v

Once installed, Nginx automatically starts as a background service (systemd) and serves a default “Welcome to nginx!” page on port 80.

3. Reading a Real Production Nginx Config Line by Line

Here is the exact configuration we built in /etc/nginx/sites-available/ops-status.conf. Let’s read every single block so nothing feels like magic:

limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

server {
    listen 80;
    listen [::]:80;
    server_name _;

    server_tokens off;

    # Security Headers
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "DENY" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # Abuse / Payload Protection
    client_max_body_size 1m;

    location / {
        limit_req zone=api_limit burst=20 nodelay;
        proxy_pass http://127.0.0.1:8081;
        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_connect_timeout 5s;
        proxy_read_timeout 30s;
    }

    location /health {
        proxy_pass http://127.0.0.1:8081/health;
        access_log off;
    }
}

A. Hiding Version Clues (server_tokens off;)

By default, Nginx sends a header saying Server: nginx/1.24.0 (Ubuntu). Telling strangers the exact version number of your software makes it easy for automated scanners to look up known bugs for that version. Setting server_tokens off; strips the version number so it only says Server: nginx.

B. Browser Security Headers

These three headers instruct the user’s browser on how to stay safe:

  • X-Content-Type-Options "nosniff" — Stops browsers from guessing file types (for example, treating a plain text upload as executable JavaScript).
  • X-Frame-Options "DENY" — Prevents shady websites from embedding your app inside an invisible <iframe> to trick users into clicking buttons (clickjacking).
  • Referrer-Policy "strict-origin-when-cross-origin" — Controls how much URL info is shared when a user clicks an external link.

C. Passing the Visitor’s Real IP (X-Real-IP & X-Forwarded-For)

Because Nginx is the one talking to your Python app on 127.0.0.1, your Python app would normally think every single user has the IP address 127.0.0.1! By adding proxy_set_header X-Real-IP $remote_addr; and X-Forwarded-For, Nginx attaches a sticky note telling your app who the real visitor is.

D. Blocking Giant Uploads (client_max_body_size 1m;)

If an attacker tries to upload a 500 MB file to an API that only expects small JSON payloads, Nginx rejects it at the door before your Python app ever wastes memory reading it.

4. How Rate Limiting Actually Works (limit_req_zone)

Look at the two rate-limiting lines in our config:

limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
...
limit_req zone=api_limit burst=20 nodelay;

Think of this like a bucket with a small hole at the bottom:

  1. $binary_remote_addr — Nginx tracks each visitor’s IP address separately (using 10 MB of RAM, enough for ~160,000 IPs).
  2. rate=10r/s — The bucket drains at 10 requests per second.
  3. burst=20 — If a real human double-clicks or loads a page with multiple assets at once, up to 20 extra requests can sit in the bucket without getting blocked.
  4. nodelay — Instead of making those 20 burst requests wait in a slow line, Nginx serves them immediately while still counting them against the bucket.
  5. If a bot floods 200 requests per second, the bucket overflows and Nginx immediately returns 503 Service Temporarily Unavailable—protecting your Python app completely.
Nginx Rate Limiting Token Bucket and Zero-Downtime Reload Diagram
Left: How rate=10r/s with burst=20 nodelay handles normal users vs. bot floods. Right: Why systemctl reload never drops active users.

5. Enabling the Config and Understanding Zero-Downtime Reloads

On Ubuntu, Nginx separates available configs from active ones using symbolic links (shortcuts):

sudo ln -sf /etc/nginx/sites-available/ops-status.conf /etc/nginx/sites-enabled/ops-status.conf
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx

Why nginx -t before reload? nginx -t tests your config for typos before touching live traffic. If you forgot a semicolon, Nginx warns you and keeps running the old working config.

Why reload instead of restart? Restarting kills Nginx and drops everyone’s open connections. Reloading keeps the master process alive: it spawns new worker processes with the updated config while old workers finish serving their current requests and exit cleanly.

6. Real Bug We Hit: The Reload Race Condition

During our live build, right after running rm /etc/nginx/sites-enabled/default and systemctl reload nginx, we immediately ran curl http://127.0.0.1/health—and got a 404 Not Found and the old “Welcome to nginx!” HTML page!

Why did that happen? Because systemctl reload is asynchronous. It returns immediately while Nginx is still handing off traffic from the old workers to the new ones. Running curl -i http://127.0.0.1/health two seconds later hit the new worker and returned:

HTTP/1.1 200 OK
Server: nginx
Content-Type: application/json
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin

{
  "status": "ok",
  "uptime_seconds": 40.99
}

Notice two things in that output: Server: nginx hides the version number, and all three security headers are present. Meanwhile, /health has access_log off; so automated health checks don’t fill up your disk with log noise.

7. Key Takeaways for Your DevOps Toolkit

  • Always bind internal apps to 127.0.0.1 and let Nginx handle public port 80 (or 443 with HTTPS).
  • Combine server_tokens off, security headers, client_max_body_size, and limit_req_zone as your baseline reverse proxy shield.
  • Always run sudo nginx -t && sudo systemctl reload nginx—never restart in production unless you have to.
  • Wait a beat (or retry) after a reload before running automated health checks so you don’t hit an exiting worker.

Leave a Comment