HTTP HEAD vs GET: curl -I, Content-Length and Timeout Traps
Use curl -I correctly, distinguish HEAD from discarded GET bodies, and troubleshoot Content-Length, 405 responses and redirects with a tested local Python lab.
Use curl -I for a real HEAD operation and curl -D to inspect headers from GET. HEAD sends no response content, even when Content-Length describes a nonempty GET representation. Discarding GET output still transfers its body. Record HTTP status, curl exit code and redirect behavior separately.
A headers-only display can hide two different requests
A download check returns Content-Length: 6, but curl reports that it downloaded zero bytes. Another check discards the output and still transfers all six bytes. Neither observation alone is contradictory: one operation requested metadata with HEAD, while the other requested the representation with GET and threw its body away locally.
This distinction matters when diagnosing link checkers, metadata probes and application routes that support GET but reject HEAD. It also matters when a command prints a plausible status and then waits for data. Before changing a timeout or blaming the server, establish the method sent and the response-handling behavior selected in the client.
The goal here is a reproducible diagnosis, not a speed comparison. The included local fixture makes ten curl transfers and checks 26 conditions using Python 3.12.14 and curl 8.5.0. It covers an ordinary resource, an omitted length, a GET-only route, a redirect and the -X HEAD trap. It does not test a CDN, TLS negotiation, HTTP/2 or production application performance.
HEAD describes a selected representation without its content
RFC 9110 defines HEAD with GET semantics except that the server must not send response content. It should provide the corresponding GET header fields, but may omit fields known only when generating the content. A Content-Length supplied for HEAD must describe the number of content octets that the corresponding GET would send, rather than the empty HEAD content.
Treat that as a metadata contract. A header-only response is useful for examining type, validators or an available length. It does not demonstrate that a complete GET transfer will succeed or that the payload can be parsed. When checking a real user journey, choose a probe that verifies the behavior the user actually needs.
A missing Content-Length on HEAD does not establish that the GET representation is empty. Likewise, a positive length on HEAD does not mean that the client should wait for that many response-body bytes. The method is part of interpreting the response. Compare like requests before declaring a metadata mismatch.
Use -I for HEAD and -D for GET response headers
The dedicated curl option -I, also spelled --head, performs a HEAD request. To inspect headers from an actual GET, use -D with a header destination and retain or discard the body separately. Lowercase -i includes response headers in the normal output; it is not the uppercase -I operation.
The following commands illustrate those choices against a reserved example URL; replace it with an endpoint you are authorized to test. They are diagnostic templates, not reported measurements from that domain. The local lab later supplies controlled endpoints and checks what curl actually did.
Discarding the body with -o /dev/null changes the local destination, not the request into HEAD. A large GET can still consume time and transfer data even when nothing appears on the terminal. Use this command when the GET response is the evidence you need, rather than assuming it has the bandwidth properties of a HEAD probe.
# Request HEAD metadata.
curl -q -sS --max-time 10 -I 'https://example.com/'
# Make a GET; save headers and the representation separately.
curl -q -sS --max-time 10 -D get-headers.txt -o response.bin 'https://example.com/'
# Make a GET; print headers and discard the received body locally.
curl -q -sS --max-time 10 -D - -o /dev/null 'https://example.com/'Source: curl official manual: head, header dump, output and status options ↗
Why -X HEAD can wait after printing a successful status
The -X option changes the outgoing method text. It does not select all the transfer behavior associated with the dedicated method option. With -X HEAD on an otherwise ordinary GET operation, curl can still expect response data that a conforming HEAD response will never send. Use -I for this task.
In the lab, the resource advertises six GET bytes and keeps the HTTP/1.1 connection open. The -X HEAD command receives status 200, downloads zero bytes and reaches its deliberately short maximum time, exiting with code 28. The -I command against the same fixture completes successfully. These are observations from this controlled server, not a prediction that every -X HEAD request always hangs.
A connection close, a zero advertised length or different response framing can change the symptom. Diagnose the option combination rather than using the presence or absence of a hang as the definition of HEAD. Raising the timeout only makes this particular mistake take longer to fail; it does not turn the command into the intended metadata probe.
Keep representation length, downloaded bytes and saved bytes separate
The fixture payload is the UTF-8 encoding of café followed by a newline. That is six bytes, although the Python string contains five characters. Content-Length is a byte count, so using the number of characters would be incorrect for this response. When writing a handler, compute the length of the encoded content you will actually send.
The lab’s GET reports six downloaded bytes and stores those same bytes. HEAD reports zero downloaded bytes while exposing the corresponding length of six. GET directed to /dev/null still reports six downloaded bytes. Those three outcomes distinguish representation metadata, received content and retained local content.
Content coding introduces another comparison boundary. When inspecting a compressed response, keep request negotiation and automatic decompression settings consistent, and identify which representation the header describes. Do not compare a saved decoded file’s length with an encoded representation length as if they were the same quantity. The local fixture intentionally uses no compression so its arithmetic remains directly inspectable.
A failed HEAD probe does not by itself prove GET is broken
The /get-only lab route deliberately returns 405 with Allow: GET for HEAD, then returns the payload for GET. This is a teaching policy inside the fixture, not evidence that any particular framework behaves that way. It makes a practical diagnostic point: record the method and status together when reporting a failing link.
If an application probe receives 405, inspect route configuration and the advertised allowed methods, then test the intended GET behavior separately. Do not silently classify a working GET resource as a broken download based solely on a HEAD rejection. Conversely, do not treat a successful HEAD as proof that a GET body is valid or complete.
The lab also demonstrates curl’s default treatment of HTTP error statuses: a 404 or 405 can still have process exit status zero when the HTTP exchange completes. That is distinct from the timeout’s nonzero transport result. An automated check should record the HTTP status as well as the command exit code and apply its own acceptance policy.
Source: curl official manual: head, header dump, output and status options ↗
Record the redirect chain before interpreting the final headers
A metadata request can stop at a redirect instead of reaching the representation you intended to inspect. In the fixture, HEAD /redirect first returns 307 and a relative Location. Adding -L follows it to /asset and produces final status 200. The header dump contains both responses, so a parser must identify which header block it is examining.
Keep a finite redirect limit and record the effective URL when investigating a real service. A redirect destination can select a different route or resource; comparing its final response to an un-followed initial response is not an equal comparison. Avoid combining custom -X methods with redirect options without understanding the resulting method policy.
This article uses a same-origin 307 to isolate HEAD behavior. It does not test all redirect codes or credential forwarding. The separate redirect guide linked below covers method and body handling in more detail. For a metadata check, start with the dedicated -I option and inspect the actual chain rather than forcing a method string unnecessarily.
Run the complete local fixture
Save the following block as head-lab.py and run python3 head-lab.py on a machine with Python 3 and curl installed. No Python packages are required. It binds only to 127.0.0.1 on an operating-system-selected port, ignores curl configuration and proxies for these local requests, and removes its temporary response files when finished.
The server dispatches GET and HEAD through the same representation handler, with explicit exceptions for the teaching routes. The payload and ETag are invented fixture values. The server is for a short local exercise, not deployment; Python’s http.server documentation describes the handler interfaces and cautions against using it as a production server.
The JSON output lists every request, its curl exit code and status/download/method metrics. Successful execution reports ten transfers and 26 passed checks. The intentional timeout is part of the expected result. Headers include varying server dates, so the test checks relevant fields rather than asserting that every response header is identical.
With -I, curl can write the received header output to its output destination as well as the separate header dump. The fixture therefore uses the download metric for the zero-content check, not an assumption that the output file must be empty. For GET, it additionally compares the saved bytes with the original payload.
import http.server, threading, subprocess, tempfile, pathlib, json
PAYLOAD='café\n'.encode('utf-8')
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version='HTTP/1.1'
def log_message(self, *args): pass
def do_HEAD(self): self.respond(True)
def do_GET(self): self.respond(False)
def respond(self, head):
if self.path=='/redirect':
self.send_response(307); self.send_header('Location','/asset'); self.send_header('Content-Length','0'); self.end_headers(); return
if head and self.path=='/get-only':
self.send_response(405); self.send_header('Allow','GET'); self.send_header('Content-Length','0'); self.end_headers(); return
if self.path not in ('/asset','/get-only','/unknown-length'):
self.send_response(404); self.send_header('Content-Length','0'); self.end_headers(); return
self.send_response(200); self.send_header('Content-Type','text/plain; charset=utf-8'); self.send_header('ETag','"demo-v1"')
if not (head and self.path=='/unknown-length'):
self.send_header('Content-Length',str(len(PAYLOAD)))
else:
self.send_header('Connection','close'); self.close_connection=True
self.end_headers()
if not head: self.wfile.write(PAYLOAD)
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Handler)
thread=threading.Thread(target=server.serve_forever,daemon=True); thread.start()
base=f'http://127.0.0.1:{server.server_port}'
checks=0;results=[]
def check(condition):
global checks
assert condition
checks+=1
try:
with tempfile.TemporaryDirectory() as directory:
root=pathlib.Path(directory)
def request(path,*options):
h=root/'headers';b=root/'body';b.unlink(missing_ok=True)
run=subprocess.run(['curl','-q','--noproxy','*','-sS','--max-time','2','-D',str(h),'-o',str(b),'-w','%{http_code}|%{size_download}|%{method}',*options,base+path],capture_output=True,text=True,timeout=4)
results.append({'path':path,'options':list(options),'exit':run.returncode,'metrics':run.stdout})
return run,h.read_text(),b.read_bytes() if b.exists() else b''
run,h,b=request('/asset');check(run.returncode==0);check(run.stdout=='200|6|GET');check(b==PAYLOAD);check('Content-Length: 6' in h)
run,h,b=request('/asset','-I');check(run.returncode==0);check(run.stdout=='200|0|HEAD');check('Content-Length: 6' in h)
run,h,b=request('/asset','-o','/dev/null');check(run.returncode==0);check(run.stdout=='200|6|GET')
run,h,b=request('/get-only','-I');check(run.returncode==0);check(run.stdout=='405|0|HEAD');check('Allow: GET' in h)
run,h,b=request('/get-only');check(run.stdout=='200|6|GET');check(b==PAYLOAD)
run,h,b=request('/unknown-length','-I');check(run.returncode==0);check(run.stdout=='200|0|HEAD');check('Content-Length:' not in h)
run,h,b=request('/redirect','-I');check(run.stdout=='307|0|HEAD');check('Location: /asset' in h)
run,h,b=request('/redirect','-I','-L','--max-redirs','3');check(run.returncode==0);check(run.stdout=='200|0|HEAD');check(h.count('HTTP/1.1')==2)
run,h,b=request('/asset','-X','HEAD','--max-time','0.3');check(run.returncode==28);check(run.stdout=='200|0|HEAD')
run,h,b=request('/missing','-I');check(run.returncode==0);check(run.stdout=='404|0|HEAD')
finally:
server.shutdown();server.server_close();thread.join()
print(json.dumps({'curl':subprocess.check_output(['curl','--version'],text=True).splitlines()[0],'requests':len(results),'checks':checks,'results':results},indent=2))Turn the result into a useful incident report
For a real failure, retain the exact command options, method, initial and effective URLs, HTTP status, curl exit code, redirect chain and relevant response fields. Record credentials and cookies only through approved secure handling; a public bug report does not need their values. Keep the request conditions consistent when comparing HEAD with GET.
Choose the next check from the evidence. A zero-byte HEAD with a positive Content-Length can be normal. A GET-only route needs a method-policy investigation. A custom-method timeout needs a corrected curl invocation. A GET that completes but contains invalid application data needs a payload-level check. These findings lead to different fixes and should not be collapsed into “the URL failed.”
Use HEAD for the metadata question it can answer. Use GET when the body transfer or its contents are the requirement. Verify both when the application promises corresponding metadata and downloadable content. That keeps a small diagnostic command from becoming a misleading health signal.
| Observed result | What it establishes | Next check |
|---|---|---|
| HEAD 200; zero downloaded bytes; length six | Metadata exchange completed | GET if content delivery matters |
| HEAD 405; GET 200 | Different route method policy in this fixture | Inspect allowed methods and route configuration |
| -X HEAD times out; -I succeeds | Client option behavior differs here | Use the dedicated HEAD option |
| GET to /dev/null downloads six bytes | Discarding output did not avoid transfer | Use HEAD only if metadata is sufficient |
| HEAD 307 before -L; 200 after -L | The redirect chain changes the target response | Inspect Location and final URL |
Your next steps
- Match the probe method to the behavior you need to verify.
- Separate representation length, downloaded bytes and saved output.
- Prefer dedicated curl options and verify status as well as exit code.
Sources & official resources
Linked resources checked on 2026-11-06. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →