Optional Extension: Enable Caching in Nginx (Reverse Proxy Lab)

1. Goal

In this extension you will:

  • Configure Nginx to cache responses from the backend pool
  • Verify that repeated requests are served from cache
  • Observe cache behavior when you change backend responses

You should add this on top of your existing loadbalance.local setup.


2. Step 1 – Define a Cache Path

Edit the main Nginx config file:

sudo nano /etc/nginx/nginx.conf

Inside the http { ... } block, add:

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m
                 max_size=100m inactive=60m use_temp_path=off;

Explanation:

  • mycache:10m – name of cache zone + metadata size
  • max_size=100m – limit cache size
  • inactive=60m – cached items not accessed for 60 minutes are removed

Save and exit.


3. Step 2 – Enable Cache in Your Server Block

Edit your site config:

sudo nano /etc/nginx/sites-available/loadbalance.local

Inside the server { ... } block, modify your location /:

location / {
    proxy_cache mycache;
    proxy_cache_valid 200 1m;
    add_header X-Proxy-Cache $upstream_cache_status;
 
    proxy_pass http://backend_pool;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

Explanation:

  • proxy_cache mycache; – use the cache zone configured earlier
  • proxy_cache_valid 200 1m; – cache HTTP 200 OK responses for 1 minute
  • X-Proxy-Cache – custom header with cache status (MISS, HIT, BYPASS, …)

Test and reload:

sudo nginx -t
sudo systemctl reload nginx

4. Step 3 – Test the Cache

4.1 Initial Request

Run:

curl -I http://loadbalance.local/

Look for the header:

X-Proxy-Cache: MISS

The first request typically results in MISS (nothing cached yet).

4.2 Subsequent Requests

Run:

for i in {1..5}; do curl -I http://loadbalance.local/; done

You should now see:

X-Proxy-Cache: HIT

This indicates the response is being served from cache.


5. Step 4 – Verify Cache Duration

  1. Wait at least 1 minute (based on proxy_cache_valid 200 1m).

  2. Call again:

    curl -I http://loadbalance.local/

You should see the status go back to MISS, then HIT again on later requests.


6. Step 5 – Observe Caching Effects

Try changing one backend to respond differently (e.g. backend 1 returns {"backend":"1-changed"}) while the cache is active.

  • You may still see the old data until cache expires.
  • This shows that clients are no longer hitting backends directly for each request.

Describe your observations in your protocol:

  • How did the X-Proxy-Cache header change?
  • When did you see updated backend responses?