curl Follow Redirects

Handle HTTP redirects in curl with the -L flag. Learn redirect chains, status codes 301/302/307/308, max redirect limits, and method preservation rules.

General

Detailed Explanation

Following Redirects with curl

By default, curl does not follow HTTP redirects. When a server responds with a 3xx status code, curl simply shows the redirect response. The -L flag tells curl to follow the redirect chain.

Basic Redirect Following

curl -L https://example.com/old-page

Without -L, you would see the 301/302 response with a Location header. With -L, curl automatically makes a new request to the URL specified in the Location header.

Understanding Redirect Status Codes

  • 301 Moved Permanently: The resource has permanently moved. Browsers cache this.
  • 302 Found: Temporary redirect. The original URL should be used for future requests.
  • 303 See Other: Redirect after a POST. The redirected request becomes a GET.
  • 307 Temporary Redirect: Like 302, but the HTTP method is preserved.
  • 308 Permanent Redirect: Like 301, but the HTTP method is preserved.

Limiting Redirects

Prevent infinite redirect loops with --max-redirs:

curl -L --max-redirs 5 https://example.com/page

The default maximum is 50 redirects. Set to -1 for unlimited (not recommended).

Viewing the Redirect Chain

Use -v to see each redirect in the chain:

curl -L -v https://example.com/short-link 2>&1 | grep "< HTTP\|< Location"

Or use -w to print redirect information:

curl -L -s -o /dev/null -w "Final URL: %{url_effective}\nRedirects: %{num_redirects}\n" \
  https://example.com/short-link

POST and Redirects

When following a redirect from a POST request, curl changes the method to GET by default (matching browser behavior). To preserve the POST method through redirects, use --post301, --post302, or --post303:

curl -L --post301 -X POST -d '{"key":"value"}' \
  -H "Content-Type: application/json" \
  https://api.example.com/endpoint

Redirect with Authentication

By default, curl strips the Authorization header when redirecting to a different host. Use --location-trusted to send credentials to all redirect targets:

curl -L --location-trusted -u user:pass https://example.com/redirect

Be cautious with --location-trusted as it may expose credentials to third-party servers.

Use Case

A developer working with URL shorteners or API gateways needs to resolve the final destination URL through multiple redirect hops while preserving authentication headers.

Try It — Curl to Code Converter

Open full tool