How to follow redirects in cURL Command Request


When you execute a cURL request to an HTTP server and if the page has been moved to another location then you will get an 3XX HTTP response.

Status CodeMeaning
300Multiple Choices
301Moved Permanently
302Found
303See Other
304Not Modified
307Temporary Redirect
308Permanent Redirect

In the case of 3XX redirect, by default cURL will not automatically follow redirects.

If you want your cURL command to follow all the redirects then you need to make use of the location flag -L or --location

Let's look at some examples, first, we just make use of -I flag to display response headers for a URL that is redirected.

% curl -I http://code2care.org 

HTTP/1.1 301 Moved Permanently
Date: Wed, 05 Jul 2023 11:37:56 GMT
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Wed, 05 Jul 2023 12:37:56 GMT
Location: https://code2care.org/
NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
Server: cloudflare
CF-RAY: 7e1f519edd19f498-BOM
alt-svc: h3=":443"; ma=86400

As you can see there was a 301 Moved Permanently response and cURL did not follow the redirect.

Now let's make use of the -L flag for the same request.

% curl -I -L http://code2care.org

HTTP/1.1 301 Moved Permanently
Date: Wed, 05 Jul 2023 11:42:26 GMT
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Wed, 05 Jul 2023 12:42:26 GMT
Location: https://code2care.org/
NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
Server: cloudflare
CF-RAY: 7e1f5834a95f0e1c-BOM
alt-svc: h3=":443"; ma=86400

HTTP/2 200 
date: Wed, 05 Jul 2023 11:42:26 GMT
content-type: text/html; charset=UTF-8
cache-control: public, max-age=2592000
content-security-policy: upgrade-insecure-requests;
display: staticcontent_sol
pagespeed: off
response: 200

As you may see that the redirect to https://code2care.org was followed and we got a HTTP/2 200 OK message.



Read more:

Location: -L or --location https://curl.se/docs/manpage.html#-L

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap