Redirect is a standard HTTP response instructing clients to look at a different URL. This is often used when the content has moved, or the URL structure has changed. There are a few types of redirects, but the most common ones are temporary redirect (HTTP status 302) and permanent redirect (HTTP status 301). HTML and JavaScript redirects are often used on web pages with meta refresh tags and windows.location respectively, but these are not HTTP redirects and are not supported by cURL.

While browsers automatically follow these redirects, cURL does not, unless instructed to. Instead, it will display the initial redirect response from the server. For many tasks, especially automating web processes or accessing APIs, it's important to be able to follow these redirects seamlessly.

cURL allows you to follow redirects automatically. You can set the maximum number of redirects or instruct it to follow all redirects for each request. You can also set the option in your .curlrc file to make it the default behavior for all requests.

Steps to make cURL automatically follow redirects:

  1. Open the terminal.
  2. Run curl against a URL with a known redirect.
    $ curl -i http://simplified.guide
    HTTP/1.1 301 Moved Permanently
    Server: awselb/2.0
    Date: Sat, 09 Sep 2023 13:46:32 GMT
    Content-Type: text/html
    Content-Length: 134
    Connection: keep-alive
    Location: https://www.simplified.guide:443/
    
    <html>
    <head><title>301 Moved Permanently</title></head>
    <body>
    <center><h1>301 Moved Permanently</h1></center>
    </body>
    </html>
  3. Use the -L option to instruct cURL to follow redirects.
    $ curl -L http://simplified.guide
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
                <!-- Google tag (gtag.js) -->
            <script async src="https://www.googletagmanager.com/gtag/js?id=G-SZLRMNXV54"></script>
            <script>
    ##### snipped
    -L, --location
           If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place.

    cURL will follow up to 50 redirects by default.

  4. Set maximum number of redirections to follow if necessary.
    $ curl -L --max-redirs 10 http://simplified.guide

    Be cautious when increasing the limit of --max-redirs to avoid potential infinite redirect loops.

    Set the value to -1 to infinitely follow redirects.

  5. Add follow redirect option to cURL's config file to change the default behavior.
     $ echo 'location' >> ~/.curlrc 
  6. Add maximum redirect option to cURL's config file.
     $ echo 'max-redirs = 10' >> ~/.curlrc 
Discuss the article:

Comment anonymously. Login not required.