State and authentication
Follow redirects with boundaries
Follow redirect chains, inspect every hop, and understand why credentials need special care across hosts.
10 minute lesson
A redirect tells the client to request another URL. The server answers with a 3xx status and a Location header pointing somewhere else. Browsers follow that pointer automatically. curl reports it but follows it only when you enable location handling with --location (short form -L).
That default is a feature. It means curl never visits a URL you didn’t ask about unless you opted in.
Inspect a chain
Inspect a two-hop chain:
curl --location --verbose https://httpbin.org/redirect/2 -o /dev/null
In the verbose output you’ll see the pattern repeat: a request, a < HTTP/2 302 response, a < location: header, then a * Issue another request line as curl moves to the next URL. Read every status and Location value. Notice the final URL and whether the hostname changes.
Two write-out variables summarize a chain without the noise:
curl --location --silent --output /dev/null \
--write-out 'hops=%{num_redirects} final=%{url_effective}\n' \
https://httpbin.org/redirect/2
# hops=2 final=https://httpbin.org/get
If num_redirects surprises you, something in the chain is doing more than you thought.
Put a ceiling on it
Two pages redirecting to each other create a loop. curl gives up after 50 hops by default, but a diagnostic command deserves a tighter bound:
curl --location --max-redirs 3 https://httpbin.org/redirect/5
This exits with code 47, “maximum redirects followed”, after the third hop. In a script, a low --max-redirs turns a misconfigured redirect loop into a fast, clear failure instead of a slow crawl through 50 requests.
The credential boundary
Here’s where redirects get dangerous. A chain can hop from the host you trust to one you never intended, and any credentials attached to the request could travel with it. curl protects you: when a redirect changes the hostname, it stops sending --user credentials and the Authorization header. The --location-trusted option disables that protection.
Do not use options that forward credentials to unrelated hosts unless you have verified the complete redirect boundary. Inspect the whole chain first, then decide.
Lesson completed