Curl Follow Redirect Example

Curl does not follow redirects unless asked. Without -L a moved URL gives you a 3xx status and an empty or tiny body, which is why a command that works in a browser can appear to return nothing.

Last updated . How this page is checked.

The command

curl -L https://httpbin.org/redirect/2

What the flags do

FlagWhat it does
-LFollow Location headers. Long form: --location.
--max-redirs NGive up after N redirects, to stop loops.
-IWith -L, print the headers of each hop.
--post301 / --post302 / --post303Keep POST as POST after that status code.
--location-trustedAlso send credentials to redirect targets on other hosts.

Seeing the chain

To understand a redirect, look at it before following it. -I shows the status and Location of the first response; adding -L prints every hop. -w can report where you ended up and how many redirects it took.

curl -sIL http://example.com/old | grep -i -E "^(HTTP|location)"

curl -sL -o /dev/null \
  -w "final: %{url_effective}\nhops:  %{num_redirects}\n" https://httpbin.org/redirect/3

What happens to the method

After a 301, 302 or 303, curl re-sends a POST as a GET with no body, the same as browsers do. 307 and 308 exist to say "repeat exactly", and curl preserves the method and body for those. So a POST that mysteriously arrives as a GET is nearly always a 301 or 302 in front of the endpoint, commonly an http to https upgrade or a missing trailing slash. Fix the URL rather than fighting the redirect.

If you truly need the POST repeated, --post301 and --post302 request that. Do not reach for -X POST: it forces the method on every hop, including a 303 that is specifically telling you to GET the result.

curl -L -d "a=1" http://example.com/api/items        # POST, then GET after a 301
curl -L --post301 --post302 -d "a=1" http://example.com/api/items

Common mistakes

  • Credentials stop at the first foreign host. -u and the Authorization header are not forwarded to a different hostname unless you add --location-trusted.
  • Headers given with -H are forwarded to every hop. Do not put secrets in custom headers on URLs you do not control.
  • JavaScript and meta-refresh redirects are invisible to curl. It only follows HTTP Location headers.

Related curl examples

More under Network behaviour

References

These links leave api-tester.com, which is independent of the projects they point to.

FAQ

How do I make curl follow redirects?

Add the -L flag. Curl then requests the URL in each Location header until it reaches a non-redirect response.

Why does my POST become a GET after a redirect?

For 301, 302 and 303 responses, curl changes POST to GET as browsers do. Request the final URL directly, or use --post301 and --post302 to keep the method.

How do I see where a URL redirects to?

Use curl -sIL URL to print the headers of every hop, or -w "%{url_effective}" to print the final URL.