Servers frequently issue HTTP redirects (e.g., 301 or 302) to guide clients to new or updated URLs, enabling dynamic resource management and content reorganization.

By default, cURL shows the redirect but does not follow it. Enabling --location instructs cURL to continue requesting until it reaches the final destination, simulating typical browser behavior.

Controlling redirect behavior prevents manual interventions, ensures reaching intended endpoints, and allows specifying --max-redirs to avoid infinite loops and maintain stable workflows.

Steps to configure cURL for following HTTP redirects:

  1. Open a terminal.
  2. Check a URL that returns a redirect.
    $ curl --include "http://example.com"
    HTTP/1.1 301 Moved Permanently
    Location: http://www.example.com
  3. Use --location to follow the redirect automatically.
    $ curl --location "http://example.com"
    <!DOCTYPE html>
    <html>
      ...
    </html>

    --location follows redirects until the final destination is reached.

  4. Limit the number of redirects with --max-redirs.
    $ curl --location --max-redirs 3 "http://example.com/multiple-redirects"

    Set a limit to avoid infinite redirect loops.

  5. Add redirection rules to ~/.curlrc for all requests.
    $ echo "location" >> ~/.curlrc

    All future requests from this user follow redirects by default.

  6. Set a global maximum number of redirects in ~/.curlrc.
    $ echo 'max-redirs = 10' >> ~/.curlrc
  7. Verify final destination content after multiple redirects.
    $ curl --location "http://example.com/multiple-redirects"

    Ensure the final output matches your expected resource.

Discuss the article:

Comment anonymously. Login not required.