How to Configure cURL to Follow 3xx Redirects

When sending HTTP requests using the command-line tool curl, the default behavior is to display the response of the requested URL, even if it returns a 3xx redirect status code. This article explains how to configure curl to automatically follow these redirects to their final destination using the -L or --location flag, limit the number of redirects to prevent infinite loops, and securely handle credentials during the redirect process.

The Basic Redirect Command

To instruct curl to follow HTTP 3xx redirects, append the -L (or --location) option to your command. When curl receives a 301, 302, 303, or 307 status code, it will automatically make a new request to the URL specified in the Location header.

curl -L http://example.com

If you only want to view the HTTP response headers to see the redirect path without downloading the entire page content, combine -L with the -I (head request) option:

curl -IL http://example.com

Limiting the Number of Redirects

To prevent curl from getting stuck in infinite redirect loops, you can set a maximum redirect limit using the --max-redirs option followed by a number. If the redirect chain exceeds this limit, curl will stop and output an error.

curl -L --max-redirs 5 http://example.com

Handling Credentials Safely

By default, when curl follows a redirect to a different host, it will not forward user credentials (username and password) provided via the -u or --user option. This is a security measure to prevent sensitive data from leaking to untrusted domains.

If you trust the target redirection hosts and need to send credentials to them, use the --location-trusted flag instead of -L:

curl --location-trusted -u username:password http://example.com

Controlling POST Redirect Methods

By default, when a POST request is redirected with a 301, 302, or 303 status code, curl converts the subsequent request to a GET request, complying with standard web specifications.

If you need to force curl to maintain the POST method through redirects, use the following options:

curl -L --post301 -X POST -d "data=example" http://example.com