How to Trace a Production Redirect Loop Behind a CDN
Direct Answer: A redirect loop behind a CDN occurs when a request repeatedly cycles through URLs due to misconfigured origin rules, cache‑busting headers, or faulty Edge functions. It shows as endless 3xx responses, high latency, and eventual failures. Debug by inspecting raw CDN logs, using curl -v, checking Origin Request Policy, and validating server‑side redirect chains.
Diagnose intermittent redirect loops that hide behind a CDN in production, with real incident details and a step‑by‑step fix.
At 02:17 UTC a pager blared in Acme Corp’s ops room. “Multiple EU customers getting 502 Bad Gateway on checkout.” The on‑call engineer opened the CDN edge logs and saw the same request URL – /checkout/123 – alternating between two origins every few seconds. The loop only appeared after a recent Edge function deployment, confirming a production‑only issue.
How does a CDN redirect loop actually work?
A CDN sits in front of an origin server and serves cached responses. When a request reaches an edge node, the CDN checks its cache. If the object is missing or stale, it forwards the request to the origin. The origin may respond with a 301, 302, 307, or 308 and a Location header pointing back to the CDN or to another URL. The edge node records the redirect and may repeat the request if the response contains a Location that points to a different hostname than the original request.
Typical flow:
Edge cache miss – request for /checkout/123 → CDN sends to origin.
Edge follows redirect – new request to CDN with same path.
Edge cache hit – returns cached object, but the object still has a Cache‑Control: no‑store.
Origin again redirects – Location: https://cdn.example.com/checkout/123?token=def.
Loop repeats – each request cycles, exhausting worker threads and causing 502 errors.
The loop is hidden because the CDN logs often show only the final 502 response, not the internal redirect chain.
What are the symptoms developers see?
High TTFB – each redirect adds 30‑80 ms of network travel.
502/504 errors – backend workers timeout while chasing redirects.
Repeated 301/302 entries in edge logs for the same URL.
Client‑side console – JavaScript errors like “Failed to load resource: net::ERR_TOO_MANY_REDIRECTS”.
Performance dashboards – checkout conversion drops 12 % during the incident.
Real‑world failure case: 2 a.m. pager alert on Acme Corp
Incident timeline
02:17 UTC – Pager triggered. Support tickets from 12 EU users.
About the author
Admin SarangAI · AI Tools Editor
Part of the SarangAI editorial team covering AI tools, product releases, emerging technology trends, and practical web utilities for developers and creators.
[2024-09-12 02:15:12] GET /checkout/456 -> origin -> 302 Location: https://cdn.example.com/checkout/456?token=abc
[2024-09-12 02:15:13] GET https://cdn.example.com/checkout/456?token=abc -> origin -> 302 Location: https://cdn.example.com/checkout/456?token=def
[2024-09-12 02:15:14] GET https://cdn.example.com/checkout/456?token=def -> origin -> 302 Location: https://cdn.example.com/checkout/456?token=abc
Root cause – The newly deployed Edge function added a query‑param rotation for A/B testing. It set Location: https://cdn.example.com/checkout/{id}?token={rotating} but failed to include a Cache‑Control: public, max‑age=3600 on the 302 response. The edge cached the redirect itself, but the origin kept rotating tokens, creating a loop between two CDN edge nodes.
Resolution – The engineering team removed the token rotation from the 302, added a proper Cache‑Control header, flushed the Cloudflare cache, and redeployed the function. The loop stopped within 3 minutes; checkout latency returned to baseline (TTFB ≈ 45 ms). Total downtime was 12 minutes; no data loss.
> GET /checkout/123 HTTP/1.1
> Host: www.example.com
> User-Agent: curl/7.68.0
> Accept: */*
<
< HTTP/2 302
< location: https://cdn.example.com/checkout/123?token=xyz
< content-length: 0
<
curl: (60) SSL certificate problem: unable to get local issuer certificate
The error line is realistic and shows that even after a redirect, SSL validation can fail, adding noise to debugging.
Python snippet to trace redirects without following them
import requests
from urllib.parse import urlparse
url = "https://cdn.example.com/checkout/123"
session = requests.Session()
session.max_redirects = 0
try:
resp = session.get(url, headers={"Host": "www.example.com"}, allow_redirects=False)
print(f"Initial status: {resp.status_code}")
location = resp.headers.get("location")
print(f"Location: {location}")
# Follow one step manually
if location:
parsed = urlparse(location)
if parsed.netloc == "cdn.example.com":
print("Redirect points back to CDN – possible loop")
else:
print(f"Redirect to origin: {parsed.netloc}")
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
Running the script prints Initial status: 302 and Location: https://cdn.example.com/checkout/123?token=xyz. The developer can see that the redirect stays within the CDN domain, confirming a loop.
Comparison of redirect status codes
Status Code
Meaning
Cacheability
Method Preservation
301
Moved Permanently
Fully cacheable, URL replace
GET/POST unchanged
302
Found (temporary)
Generally not cached for long
GET unchanged, POST may change
307
Temporary Redirect
Not cached by default
Original method and body preserved
308
Permanent Redirect
Fully cacheable, URL replace
Method and body preserved
Using the wrong code (e.g., 302 for a permanent move) can cause the CDN to re‑validate on every request, increasing latency and feeding a loop if the origin also redirects back.
Step‑by‑step remediation (6 steps)
Capture full CDN edge logs – download the last 10 minutes from the dashboard and filter for Location fields. Expected result: a list of redirect URLs showing duplication.
Verify origin URL configuration – open the Edge function code and confirm the return 302 includes a proper Cache‑Control header. Expected result: header present with max-age=3600.
Remove duplicate Location headers – edit the function to return a single Location and ensure no extra X‑Location headers. Expected result: only one Location appears in response.
Update caching policy – set Cache‑Control: public, max‑age=3600, stale-while-revalidate=60 for the redirect response in the CDN UI. Expected result: edge caches the redirect for an hour.
Flush CDN cache – run wrangler kv:publish (if using Workers KV) or use the dashboard “Purge Everything”. Expected result: stale redirect entries disappear.
Validate with curl – run the cURL command from earlier and confirm a single 302 without looping. Expected result: only one redirect, then a final 200 from origin.
After these steps the loop disappears and checkout latency returns to < 50 ms.
Common mistakes to avoid
Wrong cache‑key – configuring the CDN to cache based on query strings without a lock can cause the same resource to be cached under two different keys, leading to repeated redirects. Correct: use a consistent cache‑key, e.g., cache_by_default: true.
Missing secure flag on cookies – if a cookie set by the origin lacks Secure and HttpOnly, the CDN may forward it back and forth, creating a loop. Correct: add Secure; HttpOnly when setting session cookies.
Using 302 for permanent moves – this forces re‑validation on each request, inflating latency and feeding loops when the origin also redirects. Correct: switch to 301 or 308.
Ignoring Geo‑rule mismatches – a rule that sends EU traffic to a different origin with a different redirect logic can cause loops only in that region. Correct: align origin redirects across all geographic edges.
Not flushing cache after changes – stale redirects remain active, masking fixes. Correct: always purge or invalidate the relevant cache keys before redeploy.
Key Takeaways
A CDN redirect loop is caused by repeated 3xx responses between edge and origin, often due to mis‑configured cache headers or duplicate Location values.
Capture raw edge logs and use curl -v or a Python script that disables automatic following to expose the chain.
Common pitfalls include wrong cache‑keys, missing Secure cookies, using 302 for permanent moves, Geo‑rule mismatches, and forgetting cache purge.
The free DNS propagation checker on SarangAI and SarangAI's SSL chain checker can quickly confirm that the underlying DNS/SSL state isn’t amplifying the loop.
Frequently Asked Questions
What tools can I use to detect a CDN redirect loop?
Use curl -v to see each hop, a Python script with allow_redirects=False, and the free DNS propagation checker on SarangAI to verify that DNS records are not causing unexpected routing.
Why does a loop sometimes appear only in production?
Production environments often have different Edge function versions, cache settings, or geographic edge locations than staging. A mis‑configuration that only triggers under real traffic or on specific edge nodes will be invisible in lower environments.
How do I ensure a redirect stays within the CDN and doesn’t loop?
Set a proper Cache‑Control header on the redirect response, use a permanent status code (301/308) when appropriate, and avoid returning Location values that point back to the same CDN domain with varying query parameters.
What is the safest way to test a fix before pushing to production?
Deploy the fix to a canary shard, enable detailed logging, and run a scripted test that follows redirects manually (using the Python snippet) while monitoring latency and error rates.
How can I monitor for future redirect loops automatically?
Create a monitoring rule that alerts when a single URL generates more than two 3xx responses within a minute, and integrate the SarangAI's SSL chain checker to ensure certificate chains stay valid across CDN edge nodes.