Web Cache Poisoning vs Web Cache Deception: Secure Nginx Caching Configuration Guide

Security tutorial - IT technology blog
Security tutorial - IT technology blog

After my server got hit by SSH brute-force attacks at midnight, I became obsessed with understanding every layer of my infrastructure stack — not just the application, but the caching layer sitting in front of it. Most engineers lock down their databases and application code, then leave the CDN and reverse proxy running on default settings. That’s exactly where attackers look.

Two attack classes exploit this gap: web cache poisoning and web cache deception. Neither is theoretical — they’ve hit real production systems at PayPal, GitHub, and Cloudflare itself. What follows covers how each attack works, what genuinely mitigates them, and the Nginx configs that close both doors.

Understanding the Two Attack Vectors

Web Cache Poisoning

Cache poisoning tricks a caching server into storing a malicious response, then serving it to every subsequent user who requests that URL. The attacker doesn’t need to stay connected — the cache does the work for them.

The attack hinges on unkeyed inputs: HTTP headers that change what the server returns but aren’t included in the cache key. Some classic ones:

  • X-Forwarded-Host — many apps use this to build absolute URLs in responses
  • X-Forwarded-Scheme — triggers redirects in some frameworks
  • X-Original-URL / X-Rewrite-URL — override the request path on certain middleware stacks
  • X-Cache-Key — some CDNs expose the cache key directly in headers

Here’s how a real attack plays out: the attacker sends a request with X-Forwarded-Host: attacker.com. The backend trusts that header to construct absolute URLs, so the response includes https://attacker.com/static/main.js in a script tag. The CDN caches it under the original URL. Every visitor who loads that page now pulls JavaScript from attacker.com — and the attacker hasn’t been near the server since.

Web Cache Deception

Cache deception is the mirror image. Rather than poisoning what the cache serves, the attacker tricks the cache into storing sensitive data that should never be cached.

  1. Attacker sends victim a crafted URL: https://example.com/account/profile/nonexistent.css
  2. The web server ignores the unknown path suffix and returns the authenticated user’s profile page
  3. The CDN sees a .css extension and caches the response — many CDNs cache static file extensions by default
  4. Attacker fetches the same URL unauthenticated and gets the victim’s cached profile data

The root cause is a disagreement: the application sees a valid authenticated route; the CDN sees a .css file and stores it without question. That gap is the entire attack surface.

Approach Comparison: Mitigation Strategies

Strategy A — Strip Unkeyed Headers at the CDN Edge

The quickest fix. Strip dangerous headers at the edge before they reach your origin — no application changes needed, usually just a few lines of CDN config or Nginx proxy_set_header directives.

Pros: Fast to deploy, blocks the most common poisoning vectors immediately, zero application code changes.
Cons: Purely reactive — only protects against headers you’ve explicitly listed. Any new unkeyed input your application introduces is exposed until you update the list. Does nothing for cache deception.

Strategy B — Normalize Cache Keys Explicitly

Define exactly what a cache key is. This forces a thorough audit of every header your application uses to vary responses — which is exactly the review you should have done before shipping. Most teams haven’t.

Pros: Addresses the root cause of poisoning. The audit often surfaces other vulnerabilities along the way.
Cons: Requires deep familiarity with how your application varies responses. Easy to misconfigure and silently break legitimate caching behavior without realizing it.

Strategy C — Whitelist Cacheable Content Explicitly

Start with everything uncacheable by default. Add caching back one route at a time, only after reviewing each one. Slower to roll out, but the conservative default protects new routes automatically until someone explicitly opts them in.

Pros: Prevents cache deception by design. New routes stay protected until deliberately reviewed.
Cons: Requires ongoing maintenance as the application grows. Every performance gain is a deliberate decision per route.

Recommended Setup: Defense in Depth

Use all three in layers. Strip known dangerous headers at the edge, normalize cache keys explicitly, and whitelist cacheable content by path pattern — not by file extension globally. The layers reinforce each other.

The right balance depends on your application type:

  • Static sites / marketing pages: Aggressive caching is fine. Focus on cache key normalization and unkeyed header stripping.
  • Authenticated web apps: Use Strategy C. Never cache responses containing user-specific data unless you have explicit Vary headers and per-user cache partitioning.
  • API backends: Default to Cache-Control: no-store at the application level. Only cache idempotent, fully public GET endpoints explicitly.

Implementation Guide: Nginx Configuration

1. Strip Unkeyed and Dangerous Headers

At the Nginx layer, remove these before proxying upstream. The attacker’s injected headers never reach your application:

# nginx.conf — strip dangerous unkeyed headers before proxying
server {
    listen 443 ssl;
    server_name example.com;

    location / {
        # Strip headers attackers commonly inject
        proxy_set_header X-Forwarded-Host "";
        proxy_set_header X-Original-URL "";
        proxy_set_header X-Rewrite-URL "";
        proxy_set_header X-Forwarded-Scheme "";
        proxy_set_header X-Host "";

        # Set a known-safe host value explicitly
        proxy_set_header Host $host;

        proxy_pass http://backend;
    }
}

2. Configure Explicit Cache Keys

Use proxy_cache_key to define exactly what constitutes a unique cache entry. Nginx’s default actually excludes request headers already — being explicit just makes the intent auditable and harder to accidentally undo during future config changes:

http {
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=main_cache:10m
                     max_size=1g inactive=60m use_temp_path=off;

    server {
        location /static/ {
            proxy_cache main_cache;

            # Explicit cache key — scheme + host + URI only
            # No request headers included here
            proxy_cache_key "$scheme$host$request_uri";

            proxy_cache_valid 200 302 1d;
            proxy_cache_valid 404 1m;

            # Critical: don't cache if a session cookie is present
            proxy_no_cache $cookie_session;
            proxy_cache_bypass $cookie_session;

            proxy_pass http://backend;
        }
    }
}

3. Whitelist Cacheable Paths — Not File Extensions

This is the most direct defense against cache deception. Cache by explicit path prefix, not by file extension pattern applied globally:

server {
    # Cache ONLY under /static/ — your CDN origin-pull path for assets
    location ^~ /static/ {
        proxy_cache main_cache;
        proxy_cache_key "$scheme$host$request_uri";
        proxy_cache_valid 200 1d;

        # Static assets don't need auth cookies forwarded
        proxy_set_header Cookie "";
        proxy_pass http://backend;
    }

    # Authenticated routes — explicitly bypass cache
    location ~* ^/(account|dashboard|api|admin)/ {
        proxy_no_cache 1;
        proxy_cache_bypass 1;

        # Tell downstream CDNs not to cache either
        add_header Cache-Control "no-store, no-cache, must-revalidate" always;
        add_header Pragma "no-cache" always;

        proxy_pass http://backend;
    }

    # Default — conservative, no caching
    location / {
        proxy_no_cache 1;
        proxy_cache_bypass 1;
        proxy_pass http://backend;
    }
}

4. Enforce Cache-Control Headers at the Application Layer

Nginx alone shouldn’t be your only line of defense. Your application should send the same policy independently — if Nginx is misconfigured or bypassed, the app-level headers still protect you. Here’s an Express middleware example:

// Express middleware — explicit cache headers per route type
app.use((req, res, next) => {
    const isUserRoute = req.path.startsWith('/api/') ||
                        req.path.startsWith('/account/') ||
                        req.path.startsWith('/dashboard/');

    if (isUserRoute) {
        // User-specific or sensitive — never store in any cache
        res.set('Cache-Control', 'no-store');
        res.set('Vary', '*'); // Signals to CDNs that this response is non-cacheable
    }
    next();
});

// Static assets — cache-friendly headers
app.use('/static', express.static('public', {
    maxAge: '1d',
    setHeaders: (res) => {
        res.set('Cache-Control', 'public, max-age=86400, immutable');
    }
}));

5. Test Your Cache Configuration

Don’t trust the config — verify it. Run these after every deployment to catch misconfigurations before they reach production:

# Verify static assets have correct cache headers
curl -sI https://example.com/static/main.css | grep -i cache

# Confirm authenticated routes return no-store
curl -sI https://example.com/account/profile | grep -i cache

# Test that X-Forwarded-Host is stripped (should NOT appear in response or affect content)
curl -sI -H "X-Forwarded-Host: attacker.com" https://example.com/ | grep -i location

# Cache deception probe — append extension to auth route
# This should return 404 or redirect, NOT cached user data
curl -sI "https://example.com/account/profile/test.css"

# Debug: add this temporarily to nginx.conf to inspect the cache key
# add_header X-Cache-Debug "$scheme$host$request_uri" always;
# Remove before going to production

6. Cloudflare Cache Rules (If Using Cloudflare CDN)

If Cloudflare sits in front of Nginx, add these rules under Caching → Cache Rules in your dashboard. Cloudflare evaluates rules top-to-bottom — order matters:

Rule 1 — Bypass cache for authenticated paths:
  Match: URI Path contains "/account/" OR "/api/" OR "/admin/" OR "/dashboard/"
  Action: Cache Eligibility → Bypass cache

Rule 2 — Cache static assets from explicit path only:
  Match: URI Path starts with "/static/"
  Action: Cache Eligibility → Eligible for cache
          Edge Cache TTL → 1 day
          Browser Cache TTL → 1 day

Transform Rules — strip unkeyed headers:
  Match: All incoming requests
  Action: Remove request header → X-Forwarded-Host
          Remove request header → X-Original-URL
          Remove request header → X-Rewrite-URL

Quick Security Checklist

  • Strip X-Forwarded-Host, X-Original-URL at every proxy layer
  • Use explicit proxy_cache_key that excludes all request headers
  • Apply proxy_no_cache and proxy_cache_bypass on all authenticated routes
  • Application sends Cache-Control: no-store on every user-specific response
  • Cache static assets by path prefix, never by file extension globally
  • Run curl -sI checks after every deployment to verify headers are still correct
  • Confirm “Cache Everything” mode is NOT active globally in your CDN dashboard

These layers have held up well across the systems I manage. Cache attacks are particularly sneaky — the malicious content gets served directly from cache, so nothing suspicious shows up in your application logs. The backend never even sees the request. Most security engineers stop at the application layer and treat the cache as a performance concern. Attackers know this. Lock the caching layer down like any other public-facing component.

Share: