Limit Maximum Redirects in curl

When using curl to fetch data from the web, the tool can be configured to automatically follow HTTP redirects. However, infinite redirect loops or excessive hops can waste system resources and slow down your scripts. This article explains how to quickly limit the maximum number of redirects curl will follow using the --max-redirs option, helping you prevent performance bottlenecks and secure your network requests.

To limit redirects in curl, you must use the --max-redirs option in combination with the -L (or --location) flag. The -L flag tells curl to follow redirects, while --max-redirs defines the strict upper limit of those redirects.

Here is the basic command syntax:

curl -L --max-redirs 3 https://example.com

In this example, curl will follow a maximum of 3 redirects. If the server attempts to redirect the request a 4th time, curl will halt the operation and return an error (specifically, exit code 47, which indicates “Maximum redirects followed”).

Setting the Limit to Zero

If you set the --max-redirs limit to 0, curl will not follow any redirects at all, even though the -L flag is active:

curl -L --max-redirs 0 https://example.com

Why You Should Limit Redirects

By default, when the -L flag is enabled, curl will follow up to 50 redirects before stopping. Restricting this default behavior is highly recommended for several reasons: