Follow redirects with curl

0
7900
Follow redirects with curl

If you make requests to any website that responses with HTTP code 302, you will need to config curl to redirect requests. I will show you how to follow redirects with curl.

Follow redirects with curl

Let’s start with a real-world example of making request using curl from terminal:

$ curl https://blog.usejournal.com/enyme-testing-rip-43c7887a7246

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

If you use browser, ex. Chrome, Firefox, Safari…, you can access the page, but the above command produces only 302 Found HTTP code status.

What’s wrong with the request?

We can try to debug the request to confirm the response header.

$ curl -i https://blog.usejournal.com/enyme-testing-rip-43c7887a7246

HTTP/2 302
server: nginx
date: Tue, 26 Mar 2019 15:28:40 GMT
content-type: text/html
content-length: 154
location: https://medium.com/m/global-identity?redirectUrl=https%3A%2F%2Fblog.usejournal.com%2Fenyme-testing-rip-43c7887a7246

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

The point of interest here is the Location header,

location: https://medium.com/m/global-identity?redirectUrl=https%3A%2F%2Fblog.usejournal.com%2Fenyme-testing-rip-43c7887a7246

It looks like usejournal.com uses Medium as their publishing platform for blog.

Okay, so we need to follow the Location header, that means redirecting the request to the link specified.

To do that, we use -L or --location, to follow redirection.

$ curl -i -L https://blog.usejournal.com/enyme-testing-rip-43c7887a7246

Ah ha…check the output, now you get the expected results.

So, anytime you want to follow redirects with curl, use that option, -L, --location, it will help you.