curl runs the same everywhere, yet a handful of its flags hide behaviour that costs an hour in production. --retry already covers DNS failures and the 408, 429, 500, 502, 503 and 504 responses, so the 500 you wrapped in --retry-all-errors was never the problem, while the 404 you assumed it caught still is. --fail throws away the error body you needed for debugging, and -X GET next to -d relabels a POST without changing it.
This sheet walks through headers and request bodies, authentication, file uploads, retries, proxies and TLS certificate handling, then the exit codes you’ll meet when a transfer fails. Every block pairs a command with the output it produced, since the lab on Rocky Linux 10 ran each one in November 2026. The quick-reference table up top answers the common jobs, and the whole sheet is also a one-page PDF. For the command-syntax side of the shell, the tldr pages guide shows how to install the tldr client and keep its example pages current.
Find the curl command for the job
Use this table when you know what you need but not the syntax. Each row is tested further down with the output it produced, so you know what a success looks like before you run anything against a real API. Skim it first, then jump to the matching section for the flags around each command, since most of these flags combine with each other:
| Job | Command |
|---|---|
| GET a URL, errors visible | curl -sS https://httpbin.org/get |
| Add a request header | curl -H "X-Trace-Id: 4f9a2c" https://httpbin.org/headers |
| POST JSON | curl -H "Content-Type: application/json" -d '{"host":"web01"}' https://httpbin.org/post |
| POST a form | curl -d "user=demo&room=ops" https://httpbin.org/post |
| URL-encode a form value | curl --data-urlencode "note=retry & resume" https://httpbin.org/post |
| Basic auth | curl -u demo:password https://httpbin.org/basic-auth/demo/password |
| Bearer token | curl -H "Authorization: Bearer $TOKEN" URL |
| Upload a file | curl -F "[email protected]" https://httpbin.org/post |
| PUT a file | curl -T metrics.csv https://httpbin.org/put |
| Retry transient failures | curl --retry 3 --retry-delay 1 URL |
| Retry on any error | curl --retry 3 --retry-all-errors URL |
| Resume a download | curl -C - -o part.bin URL |
| Send through an HTTP proxy | curl -x http://127.0.0.1:3128 URL |
| Skip the proxy for one host | curl --noproxy "*" URL |
| Use a SOCKS proxy | curl -x socks5h://127.0.0.1:1080 URL |
| Trust a private CA | curl --cacert lab-ca.pem URL |
| Skip verification (last resort) | curl -k URL |
| Time a request | curl -o /dev/null -w "%{http_code} %{time_total}s" URL |
| Follow redirects | curl -L URL |
| Save and reuse cookies | curl -c jar.txt URL, then curl -b jar.txt URL |
Check the version and feature set
Flag support depends on how the binary was built, so check what yours can do before you lean on --retry-all-errors or a newer TLS option. Scripts that run across a fleet hit this constantly, because one host on an older point release quietly changes the behaviour of the whole run:
curl --version
Compatibility questions start here, so run it on the machine you actually script against rather than trusting a different box. The first line is the version and the last is the compile-time feature list:
curl 8.12.1 (x86_64-redhat-linux-gnu) libcurl/8.12.1 OpenSSL/3.5.8 zlib/1.3.1.zlib-ng brotli/1.1.0 libidn2/2.3.7 libpsl/0.21.5 libssh/0.12.0/openssl/zlib nghttp2/1.68.0 OpenLDAP/2.6.10
Release-Date: 2025-02-13
Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns ldap ldaps mqtt pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp ws wss
Features: alt-svc AsynchDNS brotli GSS-API HSTS HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM PSL SPNEGO SSL threadsafe TLS-SRP UnixSockets
The Protocols line lists everything the build speaks, and the Features line is the compile-time feature list, where HTTPS-proxy means -x accepts an https:// proxy URL. Both lines are worth pasting into an incident note, because they pin down exactly which curl behaved that way.

If a flag from this sheet comes back as an unknown option, that Features line is the first place to look. Distro builds lag upstream releases while carrying backported security fixes, so don’t expect your version string to match the latest upstream tag.
Send headers and request bodies
Everything in this section goes to httpbin.org, an echo service that repeats your request back as JSON. Reading the echo is the fastest way to confirm what curl actually put on the wire, because guesswork about headers and bodies is where most API debugging time goes. It is a public shared service, so expect rate limits and send nothing sensitive; in this lab it stood in for a real API with no side effects to worry about. Where an echo below would show an origin field with the caller’s address, that line was trimmed from the captured output, since the lab’s own IP adds nothing worth publishing.
Add request headers
-H adds a header, and it repeats once per header. Trace IDs and content negotiation are the usual jobs:
curl -s https://httpbin.org/headers -H "X-Trace-Id: 4f9a2c" -H "Accept: application/json"
Headers are easy to get wrong silently, because a typo’d name just adds a second header nobody reads. The echo shows both custom headers arriving, alongside the two defaults curl adds on every request:
{
"headers": {
"Accept": "application/json",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1",
"X-Trace-Id": "4f9a2c"
}
}
Both headers arrived as sent, and naming Accept replaced curl’s default rather than stacking a second one, which is the override working. User-Agent is the other default curl adds on its own that the echo shows. Name either in -H and your value replaces it, so a script can identify itself to an API instead of arriving as generic curl. The -A and -e flags are short forms for the two most commonly overridden headers, one flag each:
curl -s https://httpbin.org/get -A "backup-script/1.2" -e "https://internal.example.com/jobs"
Both overrides land in the echo, replacing the defaults entirely. That matters when an API gateway fingerprints clients, which is exactly what these two headers feed:
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"Referer": "https://internal.example.com/jobs",
"User-Agent": "backup-script/1.2"
},
"method": "GET",
"url": "https://httpbin.org/get"
}
Gateways and rate limiters often key off exactly these two headers, so naming your script here beats arriving as anonymous curl. When a provider throttles by user agent, this line is also where you find out that your script, not the network, is the one being slowed.
POST JSON
-d sends a body and switches the method to POST on its own, the part people miss. Add the Content-Type header as well, because curl’s default for -d is application/x-www-form-urlencoded and plenty of APIs reject that:
curl -s https://httpbin.org/post -H "Content-Type: application/json" -d "{\"host\":\"web01\",\"port\":9100}"
Content-Type mistakes are the classic POST failure, since the body arrives but the API reads it as a form. The echo proves the header and the body both made it, and httpbin even parses the JSON for you:
{
"args": {},
"headers": {
"Accept": "*/*",
"Content-Length": "28",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "POST",
"url": "https://httpbin.org/post",
"data": "{\"host\":\"web01\",\"port\":9100}",
"files": {},
"form": {},
"json": {
"host": "web01",
"port": 9100
}
}
The echo repeats the JSON in data and the header in headers.Content-Type, so you have proof the API saw what you intended. When an API claims it never got your payload, this echo settles whether the problem was on your side of the wire.

Adding -X POST here changes nothing, because -d already made it a POST. Worse, -X GET next to -d just relabels a POST as GET while the body still goes out. Leave -X out unless the method has no body flag of its own, like DELETE:
curl -s https://httpbin.org/delete -X DELETE
The echo comes back with method: DELETE and an empty data field, which is the whole contract for most delete endpoints.
POST forms and encode values
Plain -d pairs are what a browser form posts by default. The moment a value contains &, = or a space, switch to --data-urlencode, which encodes the value for you:
curl -s https://httpbin.org/post -d "user=demo&room=ops"
curl -s https://httpbin.org/post --data-urlencode "note=retry & resume"
Both requests post the same kind of body, so the difference hides in the value itself. Run the pair in order and compare the form block of each echo:
{
"args": {},
"headers": {
"Accept": "*/*",
"Content-Length": "18",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "POST",
"url": "https://httpbin.org/post",
"data": "",
"files": {},
"form": {
"room": "ops",
"user": "demo"
},
"json": null
}
{
"args": {},
"headers": {
"Accept": "*/*",
"Content-Length": "21",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "POST",
"url": "https://httpbin.org/post",
"data": "",
"files": {},
"form": {
"note": "retry & resume"
},
"json": null
}
The second request delivered the value with its space and ampersand intact, which plain -d would have cut at the &. That truncation is silent, so the first symptom is usually a backend seeing half a value rather than any error.

Combining the same flag with -G turns POST data into GET query parameters instead, which is the clean way to build a search-style URL without hand-escaping anything. Search endpoints with long filters come out copy-pasteable this way, ready to drop into a bug report:
curl -s -G https://httpbin.org/get --data-urlencode "q=curl retry flags" --data-urlencode "page=2"
Query strings built by hand are where spaces and ampersands go to die, so let curl do the encoding. The args object in the echo is the query string it assembled from the two pairs:
{
"args": {
"page": "2",
"q": "curl retry flags"
},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "GET",
"url": "https://httpbin.org/get?q=curl+retry+flags&page=2"
}
The url field shows the query string curl built, spaces turned into + and nothing truncated. The flag only encodes what it places in the query string, so a messy value in a URL path still needs escaping by hand.
Inspect a response
-I runs a HEAD request, so you get headers only. That is the cheap way to check a content type or an expiry date before committing to a download:
curl -sI https://httpbin.org/get
Nothing but status line and headers comes back, which makes this the cheapest possible reachability check. The body is genuinely absent, not just hidden:
HTTP/2 200
access-control-allow-credentials: true
access-control-allow-origin: *
access-control-expose-headers: Retry-After, RateLimit, RateLimit-Policy
content-length: 204
content-type: application/json
x-content-type-options: nosniff
date: Sat, 07 Nov 2026 04:19:30 GMT
When you want headers and body of a real GET, keep the request as GET and print the headers above the body with lowercase -i. HEAD is a different request, and some servers answer it differently, so a HEAD test can lie about what a GET will return. When a cache or a load balancer sits in the path, the GET may even hit a different backend.
Authenticate requests
Basic auth
-u user:password builds the Authorization header for you, base64 encoding included. Run it against httpbin’s basic-auth endpoint, once with the right password and once with a wrong one:
curl -s -u demo:s3cretPW https://httpbin.org/basic-auth/demo/s3cretPW
curl -s -w "\nhttp_code=%{http_code}\n" -u demo:wrong https://httpbin.org/basic-auth/demo/s3cretPW
Auth failures are HTTP responses like any other, which is what makes them dangerous in scripts. Run it once right and once wrong, and both look like success from the exit code alone. Only the status line tells them apart, so branch on -w output rather than the exit code:
{
"authenticated": true,
"user": "demo",
"authorized": true
}
http_code=401
A wrong password came back as HTTP 401, not as a curl error, so a bare curl exits 0 and the script carries on as if the upload worked. One bad credential can therefore poison a whole pipeline without a single error message, because every stage downstream sees valid output. That silent success is why --fail belongs in every scripted curl call, covered near the end.
Bearer tokens
Bearer auth is just a header, so nothing special happens on the wire. Keep the token out of shell history by reading it into a variable first, because everything on the command line ends up in logs:
TOKEN=$(pass show api/prod)
curl -s https://httpbin.org/bearer -H "Authorization: Bearer $TOKEN"
A token pasted wrong fails in confusing ways, so confirm what the server actually received. httpbin echoes it back:
{
"authenticated": true,
"token": "eyJhbGciOi.demo.sig"
}
All three basic auth runs land on one screen, the success, the 401 and the netrc variant further down. Only the credential changes between them, which is what makes the 401 easy to miss:

For anything beyond a quick call, move the credential into a .netrc file so it stays out of the command line and the process list. curl matches entries by hostname and does not check the file’s permissions, so lock it down yourself, because the password sits in plain text:
- Write the entry:
printf "machine httpbin.org login demo password s3cretPW\n" > ~/.netrc - Lock it down with
chmod 600 ~/.netrc - Call the API with
curl -s --netrc https://httpbin.org/basic-auth/demo/s3cretPW
{
"authenticated": true,
"user": "demo",
"authorized": true
}
GitHub’s API follows the same pattern with a personal access token, and a revoked or wrongly scoped token shows up as a 401 there too. The GitHub CLI cheat sheet covers the gh equivalent if you would rather not hand-roll the header.
Upload files
Multipart upload with -F
-F builds a multipart/form-data body, the format a browser sends from an upload form, and @ reads a file from disk. The lab uses a three-line /home/joshua/metrics.csv, and extra fields ride along in the same request:
curl -s https://httpbin.org/post -F "file=@/home/joshua/metrics.csv" -F "note=weekly pull"
File uploads fail quietly in the other direction, because a missing @ makes curl post the literal path as text. The echo separates the two, the files object carrying the CSV and the form object the extra field. A wrong flag turns a whole file into a one-line string, so the echo is the only place that shows it:
{
"args": {},
"headers": {
"Accept": "*/*",
"Content-Length": "362",
"Content-Type": "multipart/form-data; boundary=------------------------jbcWw1qy1FJMmSJNQ1HkoE",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "POST",
"url": "https://httpbin.org/post",
"data": "",
"files": {
"file": "host,cpu,mem\nweb01,42,68\nweb02,17,31\n"
},
"form": {
"note": "weekly pull"
},
"json": null
}
The echo shows the filename, the content type curl guessed from the extension, and the note field travelling with it. Some APIs demand a specific filename or media type, and the parameter syntax overrides both without copying the file:
curl -s https://httpbin.org/post -F "upload=@/home/joshua/metrics.csv;filename=report.csv;type=text/csv"
Same bytes, different envelope, and nothing in the response body tells you which name landed. Only the metadata lines in the echo reveal the rename:
{
"args": {},
"headers": {
"Accept": "*/*",
"Content-Length": "237",
"Content-Type": "multipart/form-data; boundary=------------------------9w1UiWLocwixYKx2mVQzrQ",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "POST",
"url": "https://httpbin.org/post",
"data": "",
"files": {
"upload": "host,cpu,mem\nweb01,42,68\nweb02,17,31\n"
},
"form": {},
"json": null
}
The second echo keeps the upload field name, but the server-side files key no longer tells you what the caller called the file. The rename lives only in the multipart metadata, which is why pipelines that log the original filename need it sent explicitly.

When an intake pipeline checks names, send the override and the checks keep passing. The file itself never moves, so nothing that reads it from disk notices the difference.
PUT with -T
PUT endpoints and WebDAV take -T, which sends the file as the whole body and switches the method to PUT. A hyphen in place of the filename reads stdin, so a generated file never touches disk:
curl -s https://httpbin.org/put -T /home/joshua/metrics.csv
echo "quick note from ops" | curl -s https://httpbin.org/put -T -
Read both echoes, because the second one’s headers give away how the body travelled. Streaming shows up there, not in the payload, so Transfer-Encoding: chunked is the tell for stdin input:
{
"args": {},
"headers": {
"Accept": "*/*",
"Content-Length": "37",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "PUT",
"url": "https://httpbin.org/put",
"data": "host,cpu,mem\nweb01,42,68\nweb02,17,31\n",
"files": {},
"form": {},
"json": null
}
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"Transfer-Encoding": "chunked",
"User-Agent": "curl/8.12.1"
},
"method": "PUT",
"url": "https://httpbin.org/put",
"data": "quick note from ops\n",
"files": {},
"form": {},
"json": null
}
The stdin PUT shows up as Transfer-Encoding: chunked, because curl streams it without knowing the length in advance. A server that rejects chunked bodies needs a request with a declared length, and only a real file gives you that, since no pipe carries one. Reach for -T localfile instead of stdin against those servers.
Retry failed requests
--retry N retries a failed transfer up to N times, but only for what curl classes as transient. The default set is timeouts, DNS resolution failures, and the HTTP responses 408, 429, 500, 502, 503 and 504, plus FTP 4xx replies. The curl manual page lists the HTTP codes and FTP replies, and curl’s source adds the DNS resolution failures to the always-retry set. That was the set in 8.12.1, the release this sheet was tested on, and 8.17.0 later added the Cloudflare-style 522 and 524 responses to it. A 503 lands inside the set, so run it against a deliberately broken endpoint and watch the attempts stack up:
curl -sS --retry 3 --retry-delay 1 --fail -o /dev/null -w "final: %{http_code}\n" https://httpbin.org/status/503
Watch what the loop actually does instead of assuming, because the attempt count surprises people. Four tries, one error line each, and the final status at the end. The initial attempt plus three retries makes four, so --retry 3 does not mean three total attempts:
curl: (22) The requested URL returned error: 503
curl: (22) The requested URL returned error: 503
curl: (22) The requested URL returned error: 503
curl: (22) The requested URL returned error: 503
final: 503
Each curl: (22) The requested URL returned error: 503 line is one attempt, and the --fail in front is what surfaces them, because a bare --retry on a script-visible 503 would fail quietly. Under --fail the process also exits 22, so the script can branch on the outcome. Two flags tune the loop. --retry-delay 1 fixes the wait at one second instead of curl’s own exponential backoff, though it does not override a Retry-After header the server sends, and --retry-max-time 30 puts a hard ceiling on the total window, which matters in a script that has to finish.
What the default set leaves out is where the trap hides. A refused connection ends the loop after one attempt, because curl treats ECONNREFUSED as permanent unless you pass --retry-connrefused. Connection resets are not retried either, and neither is any 4xx short of 408 and 429, so a 404 or 401 never re-runs even when the API you are polling is flaky. The wide hammer for all of that is --retry-all-errors, which retries on any error at all:
curl -sS --retry 2 --retry-all-errors --retry-delay 1 --fail -o /dev/null -w "final: %{http_code}\n" https://httpbin.org/status/500
The 500 needs no widening at all, since it sits in the default transient set, so read this run as the sledgehammer flag being exercised rather than as a fix. The loop shape it produces is the same one any retry produces:
curl: (22) The requested URL returned error: 500
curl: (22) The requested URL returned error: 500
curl: (22) The requested URL returned error: 500
final: 500
Where the flag genuinely earns its place is the long tail the default set skips: a 404 that --fail turns into exit 22, a reset connection mid-transfer, a TLS handshake failure. For refused connections alone, the narrower --retry-connrefused avoids the sledgehammer. The manual page warns against putting --retry-all-errors in a curlrc for a reason, since retrying POSTs against APIs that are not idempotent can double-create resources. Keep it for reads and idempotent writes.

Pair retries with a deadline so a hung transfer can’t stall a script. --max-time caps each attempt, so four attempts of two seconds plus three one-second delays give up after about eleven seconds, as the four timeout lines show. --connect-timeout 5 caps only the connection phase, which separates an unroutable network from a slow server.
curl -sS --retry 3 --retry-delay 1 --max-time 2 -o /dev/null https://httpbin.org/delay/3
The delay endpoint needs three seconds to answer, so the two-second cap cuts every attempt short. Each try gets its own window, which is what the four timeout lines count. The deadline multiplies across retries rather than collapsing the whole loop, so budget for it in the caller:
curl: (28) Operation timed out after 2002 milliseconds with 0 bytes received
curl: (28) Operation timed out after 2002 milliseconds with 0 bytes received
curl: (28) Operation timed out after 2000 milliseconds with 0 bytes received
curl: (28) Operation timed out after 2001 milliseconds with 0 bytes received
The four timeout lines confirm each attempt got its own two-second window before the next one started, so the deadline multiplies rather than collapsing the loop. When the ceiling has to be total, put --retry-max-time on the same command.
Resume an interrupted download
-C - tells curl to look at what is already on disk and ask the server for the rest. This lab served a 60 KB file from the local nginx on port 8080, because the resume needs a server that supports byte ranges, which any static file server does. Three commands tell the whole story:
- Cut a download off at two seconds, part way through the file:
curl -sS --limit-rate 3k --max-time 2 -o part.bin http://127.0.0.1:8080/big.bin - Check the partial size with
ls -l part.bin - Resume from that byte with
curl -sS -C - -o part.bin http://127.0.0.1:8080/big.bin
curl: (28) Operation timed out after 2000 milliseconds with 8960 out of 60000 bytes received
-rw-r--r--. 1 joshua joshua 8960 Nov 7 04:21 part.bin
-rw-r--r--. 1 joshua joshua 60000 Nov 7 04:21 part.bin
The timeout line even reports how much of the file landed, 8960 of 60000 bytes, and the second run started exactly there and completed it, no extra config needed. That byte count is what -C - reads, so any interruption curl reported honestly can be resumed the same way. For plain file downloads rather than API calls, wget does the same job with -c, and the wget cheat sheet covers its resume, mirror and retry flags.

Range support is the precondition: the runbook’s first resume attempt targeted httpbin’s /bytes endpoint, which ignores the Range header, and curl gave up with error 33, the byte ranges unsupported failure. That is why the demo targets nginx, which honours ranges, and it made -C - work as shown. A server that ignores the header entirely will instead resend the whole file and overwrite your partial, which turns a recovery into a re-download, so check the resumed file’s size rather than trusting the exit code.
Send traffic through a proxy
-x points curl at a proxy, and the protocol prefix in the URL picks the proxy type. This test went through a local Squid proxy on port 3128:
curl -s -x http://127.0.0.1:3128 https://httpbin.org/get
Nothing in the response betrays the proxy, because from the client side it is indistinguishable from a direct fetch. That invisibility is the point, and also why proxy problems are so confusing to debug. When a request works without -x and fails with it, start at the proxy’s own logs rather than at curl:
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "GET",
"url": "https://httpbin.org/get"
}
For an HTTPS target the proxy only relays bytes, so the end-to-end TLS session stays between you and the destination, which the echo confirms. If your environment already exports https_proxy, curl honours it with no flags at all, and --noproxy punches a hole for hosts that must not go through it:
curl -s --noproxy "*" http://127.0.0.1:8080/big.bin -o /dev/null -w "%{http_code} %{size_download} bytes\n"
export https_proxy=http://127.0.0.1:3128
curl -s https://httpbin.org/get | head -8
unset https_proxy
The sequence runs the direct fetch first, before any proxy variable exists, then exports https_proxy to show the environment pickup, then cleans it up. Read the output in that order:
200 60000 bytes
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "GET",
The first line is the direct baseline, and it looks unremarkable precisely because no proxy variable is set yet. Once https_proxy is exported, the same style of call rides the proxy with no flags, which is the moment --noproxy "*" becomes the escape hatch for a host that must not go through it. Proxy environment variables are worth setting properly once instead of per command, and the guides on system-wide proxy settings on RHEL family systems and setting a system-wide proxy on Ubuntu and Debian cover both.
SOCKS proxies take the same -x flag with a socks5h:// prefix. The trailing h matters, because it sends the hostname to the proxy for DNS resolution, so names your local resolver can’t answer still work. Any SSH server you can reach gives you one, in three steps:
- Open the tunnel with
ssh -D 1080 -N -f [email protected] - Point curl at it:
curl -x socks5h://127.0.0.1:1080 https://httpbin.org/get - Close it when done with
pkill -f "ssh -D 1080"
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"User-Agent": "curl/8.12.1"
},
"method": "GET",
"url": "https://httpbin.org/get"
}
The echo is where you would confirm the exit: its origin field carries the address httpbin saw, which for a tunneled request is the jump host’s rather than yours, and that line is trimmed from every capture in this sheet. Run that check yourself before pointing a real integration at the tunnel, because a plain socks5:// without the h fails on exactly the names this setup exists for.

More tunnel flags and port-forwarding patterns live in the SSH commands cheat sheet. The same -D flag carries dynamic forwards and -L the fixed ones, so one jump host usually covers every path a script needs.
Verify TLS certificates properly
Point curl at a server whose certificate was signed by a CA that isn’t in your trust store, and you get the most recognisable curl error there is. Private CAs are normal for internal services, so the error usually means deployment, not attack:
curl -sS https://127.0.0.1:8443/get
Verification fails closed, which is the behaviour you want, and the error even points at the docs page that explains the trust store. Nothing leaves your machine when the handshake fails, so a corporate proxy with its own root CA is the other common source of this exact error:
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html
curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the webpage mentioned above.
The fix that keeps verification on is --cacert with the CA that signed the server’s certificate. This lab runs nginx on port 8443 behind a private CA, so the same request works as soon as the CA is passed in. The verbose view then proves who was actually verified:
curl -s --cacert /etc/pki/lab/lab-ca.pem https://127.0.0.1:8443/get
curl -sv --cacert /etc/pki/lab/lab-ca.pem https://127.0.0.1:8443/get 2>&1 | grep -Ei "subject|issuer|SSL connection"
Passing the CA is all it takes, and the request succeeds without any weakening of the check. The verbose second call then names the negotiated TLS version, the subject and the issuer:
lab-server-ok
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 / X25519MLKEM768 / RSASSA-PSS
* subject: CN=localhost
* subjectAltName: host "127.0.0.1" matched cert's IP address!
* issuer: CN=Lab CA
The verbose lines come from curl’s TLS layer on stderr, and they name the TLS version and cipher actually negotiated, which is the fastest way to answer what a server is really running. That proof matters when a client somewhere insists on an old cipher and you need to show what the server actually offers, because the negotiation decides it on the spot.

To force a minimum version, use --tlsv1.2 (or --tlsv1.3), which fails the connection outright against a server that won’t negotiate it. Failing loudly beats silently falling back to a protocol your security team already retired:
curl -s --cacert /etc/pki/lab/lab-ca.pem --tlsv1.2 https://127.0.0.1:8443/get
Version floors are cheap insurance against downgrade negotiation. With the floor set at a version the lab server speaks, the body comes back as usual:
lab-server-ok
-k / --insecure skips the certificate check and makes the error go away, which is exactly the problem, because it silently accepts anything presented. Limit it to throwaway tests, never to scripts that carry credentials. Building a private CA and issuing server certificates is its own workflow, covered in the OpenSSL cheat sheet.
Read the response and the errors
curl is quiet by default, with a progress meter on a terminal and nothing at all when output is redirected, which is exactly how errors vanish unnoticed in cron jobs. -s silences the meter and -S shows errors anyway, so -sS is the standard pair for anything scripted. Add both from the first draft of a script and you never debug an invisible failure, because the error reaches stderr the moment the transfer goes wrong.
The default failure mode hides real problems. A 404 response body still gets written and the exit code stays 0, so a script happily processes an error page as if it were data. --fail exits 22 on an HTTP error and throws the body away, while --fail-with-body keeps it so you can read what the API actually said. Cron jobs are where this bites hardest, because nobody is watching the output when it happens:
curl -sS --fail https://api.github.com/nonexistent-endpoint-4153
curl -sS --fail-with-body https://api.github.com/nonexistent-endpoint-4153
Same endpoint, same 404, two very different payloads for the caller. The second one tells your ops channel why the request failed:
curl: (22) The requested URL returned error: 404
curl: (22) The requested URL returned error: 404
{
"message": "Not Found",
"documentation_url": "https://docs.github.com/rest",
"status": "404"
}
For monitoring, the -w write-out format prints variables after the transfer, including timings you’d otherwise need a browser panel for. That makes it the standard probe from cron, since the numbers arrive in a form awk can read without any scraping:
curl -s -o /dev/null -w "%{http_code} %{time_total}s %{size_download} bytes %{speed_download} B/s\n" https://httpbin.org/bytes/100000
Status, duration, size and throughput in a single parseable line. That is everything a monitor needs about the transfer:
200 1.262640s 100000 bytes 79199 B/s
Each variable is independent, so a status line only carries the ones the monitoring actually reads. Mixing them in any order works, which makes -w easy to fit into an existing check:
| Variable | What it prints |
|---|---|
%{http_code} | Final HTTP status code |
%{time_total} | Whole transfer, seconds |
%{time_connect} | TCP connect only, useful to split network from server time |
%{time_starttransfer} | Until the first response byte arrives (TTFB) |
%{size_download} | Body bytes received |
%{speed_download} | Download throughput, bytes per second |
%{num_redirects} | Redirects followed with -L |
%{redirect_url} | Where the server said to go next |
%{exitcode} | curl’s exit code (7.75 and newer) |
Redirects need a decision, because curl does not follow them by default. Without -L you can inspect where a URL wants to send you, and with it curl replays the request at each hop, which is what the second command counts:
curl -s -o /dev/null -w "%{http_code} -> %{redirect_url}\n" https://httpbin.org/redirect/2
curl -sL -o /dev/null -w "%{num_redirects} hops, final %{http_code}\n" https://httpbin.org/redirect/2
Following redirects blindly can mask a loop or a login bounce, so look before you follow. The first line shows where the server wanted to send the request, and the second follows both hops to a 200. A redirect to a login page shows up right there, before your script posts credentials into it:
302 -> https://httpbin.org/relative-redirect/1
2 hops, final 200
Cookies work in two halves. -c writes a jar file after a response sets one, and -b sends the jar back on the next request, which is how a login-then-fetch pair of calls keeps its session alive across separate commands:
curl -s -c jar.txt https://httpbin.org/cookies/set/flavor/chocolate > /dev/null
curl -s -b jar.txt https://httpbin.org/cookies
Sessions survive between commands only because the jar persists them. The second call shows the cookie the first one stored, read back out of the jar. A login followed by a fetch is just two commands sharing one file, so no session state lives inside curl itself:
{
"cookies": {
"flavor": "chocolate"
}
}
The second call sends only the jar, so anything the server set on an earlier call stays out of the request. Delete the jar between test runs when you want a clean session, or share one deliberately to reuse an authenticated session from a script.
Read the exit code
Every curl failure maps to a numeric exit code, and the number tells you which layer broke, so a script can branch on it directly. These three were captured in this lab:
curl -sS https://no-such-host-4153.invalid/; echo "exit=$?"
curl -sS http://127.0.0.1:9; echo "exit=$?"
curl -sS --max-time 2 https://10.255.255.1/; echo "exit=$?"
Failures live at different layers, name resolution, the TCP connection and the wait itself. The exit codes separate them cleanly, which is what a script branches on. A 6 or a 28 is worth retrying later, so the same script can wait one out and page on the other:
curl: (6) Could not resolve host: no-such-host-4153.invalid
exit=6
curl: (7) Failed to connect to 127.0.0.1 port 9 after 0 ms: Could not connect to server
exit=7
curl: (28) Connection timed out after 2002 milliseconds
exit=28
| Exit code | Meaning | Usual cause |
|---|---|---|
| 6 | Couldn’t resolve host | DNS broken, typo, or no resolver in the container |
| 7 | Failed to connect | Service down, wrong port, firewall |
| 22 | HTTP error with --fail | 4xx or 5xx response |
| 28 | Operation timed out | Slow or filtered network, missing --max-time |
| 35 | SSL connect error | Handshake failure, protocol mismatch |
| 60 | Peer certificate can’t be authenticated | Private CA not passed, wrong hostname, expired cert |
Codes 6 and 28 mean retry later, and 7 means the service is down. Codes 22 and 60 mean the request itself is wrong, so retrying won’t help until something changes.

Fix common curl errors
These are the failures this lab hit while testing the flags above, each with the fix that worked, so you can match an error to a cause without guessing. Error 60 and the timeout lines came straight out of the runbook at the top, and the fixes are the same ones this page demonstrates:
curl: (60) SSL certificate problem: unable to get local issuer certificate
The server presented a certificate signed by a CA your trust store doesn’t have, which is normal for internal services. Don’t reach for -k first. Export the internal CA and pass it with --cacert, as shown above, and if the certificate is managed by your OS package manager, updating the trust bundle (ca-certificates on the Debian family, the same package plus update-ca-trust on the RHEL family) can fix it without any curl flag at all.
curl: (6) Could not resolve host
DNS didn’t answer. In a container this is usually the image having no resolver configured, and on a VPN it’s a split-DNS setup where the internal zone goes to the wrong server. Test with a name you know resolves, then check /etc/resolv.conf before blaming curl.
curl: (28) Operation timed out
Nothing answered in time. Without --max-time curl waits indefinitely, and a missing timeout is how scripts hang for hours in a queue. Add --connect-timeout as well, because it distinguishes a network that can’t route from a server that accepts connections and never responds.
curl: (22) The requested URL returned error: 4xx/5xx
This one only appears with --fail or --fail-with-body, and the number after the message is the HTTP status. That is the point of the flag, since the exit code carries the status into your script’s error handling. Switch to --fail-with-body when you need the API’s error message from the body.
Empty output and exit 0 on an error page
The silent failure. curl saved an HTML error page into your JSON file and exited 0, so nothing downstream complained until the parser choked. One move fixes it, curl -sSf URL -o out.json, where f is short for --fail and stops the pipeline before anything reads garbage.