How To Follow Redirects with Curl?

The HTTP protocol provides different attributes and behaviors where one of them is Redirection. HTTP redirect is used to redirect a request from a specific URL to another URL. The redirect can be applied temporarily or permanently. The curl is a popular command-line-based tool to make HTTP requests which also supports the HTTP redirect feature. In this tutorial, we will learn how to follow HTTP redirects with the curl command.

cURL redirect

In a simple form, the cURL command can follow redirects by using the -L option. The -L option comes from the Location the attribute of the HTTP which is used to specify the new URL or Location for the request. In the following example, we make a request to the “https://wisetut.com” but we also follow if there is a redirect by using the -L option.

$ curl -L https://wisetut.com

Set Maximum Redirects for cURL

The redirection has no limits which means a newly redirect URL may also provide a new redirect and so on. Event two URLs may have a recursive redirect where each of them can redirect to each other which creates an infinite loop of redirects. So this infinite or lots of redirects can be prevented by setting the maximum redirect count limit for the curl command. The maximum count of redirects can be specified with the --max-redirs option. In the following example, we set the maximum redirect count as 5.

$ curl -L --max-redirs 5 https://wisetut.com

Enable Infinite Redirects for cURL

By default, the cURL command has a protection mechanism to prevent infinite loops which is a maximum of 20 redirects. This means if there are more than 20 redirects the request is canceled. This limit can be disabled and infinite redirects can be enabled by using the –max-redirs option setting -1. In the following example, we disable the cURL default redirection limit which is 20.

$ curl -L --max-redirs -1 https://wisetut.com

Sent HTTP Credentials (Username and Password) for cURL Redirect

HTTP provides basic authentication features where username and password are used to login or authenticate for the specified URL. In some cases, we may need to use HTTP authentication with the cURL redirects but by default to sending username and password to another URL is insecure. So we can approve the username and password resubmission to the redirected URL by using the --location-trusted option.

$ curl -L --location-trusted --user "ismail:12345" https://wisetut.com
See also  wget Command Tutorial with Examples

Leave a Comment