Curl - Follow a 302 redirect using the -L or --location option

by
Jeremy Canfield |
Updated: February 01 2023
| Curl articles
Let's say you are using curl to issue a GET request and 302 Found is being returned, perhaps something like this.
~]# curl http://www.example.com/api
> GET /api HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.example.com
> Accept: */*
>
< HTTP/1.1 302 Found
< Location: http://www.example.com/api/
< Content-Length: 0
<
The curl man page has the following.
-L, --location
(HTTP/HTTPS) 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. If used together with -i, --include or
-I, --head, headers from all requested pages will be shown. When
authentication is used, curl only sends its credentials to the
initial host. If a redirect takes curl to a different host, it
won't be able to intercept the user+password. See also --locaâ€
tion-trusted on how to change this. You can limit the amount of
redirects to follow by using the --max-redirs option.
When curl follows a redirect and the request is not a plain GET
(for example POST or PUT), it will do the following request with
a GET if the HTTP response was 301, 302, or 303. If the response
code was any other 3xx code, curl will re-send the following
request using the same unmodified method.
Often, simply including the -L or --location flag will resolve this issue.
~]# curl --location http://www.example.com/api
> GET /api HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.example.com
> Accept: */*
>
< HTTP/1.1 302 Found
< Location: http://www.example.com/api/
< Content-Length: 0
<
> GET /api/ HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.example.com
> Accept: */*
>
< HTTP/1.1 200 OK
< Age: 409564
< Cache-Control: max-age=604800
< Content-Type: text/html; charset=UTF-8
< Date: Wed, 21 Oct 2020 02:47:07 GMT
< Etag: "3147526947+ident"
< Expires: Wed, 28 Oct 2020 02:47:07 GMT
< Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
< Server: ECS (ord/573B)
< Vary: Accept-Encoding
< X-Cache: HIT
< Content-Length: 1256
Did you find this article helpful?
If so, consider buying me a coffee over at