Troubleshoot HTTP gzip: Content-Encoding, Vary and curl
Diagnose gzip decoding errors, missing Content-Encoding, double compression and cache variants. Compare coded and decoded bodies with curl and a tested local lab.
An HTTP compression problem is usually a mismatch between the selected representation, its metadata and the decoding performed by a client or intermediary. Keep three observations separate: what Accept-Encoding offered, what Content-Encoding declares, and which bytes your tool actually saved. This guide shows how to compare those observations without confusing gzip with HTTP framing, then reproduces several failures in a disposable loopback lab.
Identify which layer changed the bytes
Content-Type describes the media type, such as text/plain or application/json. Content-Encoding describes a coding applied to that representation, such as gzip. The decoded result can therefore be JSON even though the response body transferred over the connection contains gzip-coded bytes. A filename extension or a familiar Content-Type does not establish whether the saved body is compressed.
Transfer-Encoding belongs to a different layer. In HTTP/1.1, chunked framing divides a message body for transfer; it is not gzip compression. A client can remove chunk framing while leaving content coding intact. Do not treat every byte sequence omitted from a saved file as decompression, and do not apply HTTP/1.1 chunk terminology indiscriminately to HTTP/2 or HTTP/3.
For troubleshooting, label each artifact by what it contains: received headers, content-coded body, or decoded body. A normal curl download without --compressed generally gives you the content-coded body after ordinary transfer decoding. It is not a raw capture of TCP, TLS, HTTP headers and chunk boundaries. That distinction matters when comparing byte counts.
Source: RFC 9112: HTTP/1.1 transfer coding and chunked framing ↗
A request header and a decoder are separate choices
Adding -H "Accept-Encoding: gzip" asks for a gzip response but does not by itself enable curl automatic content decoding. The --compressed option both requests supported compression and enables decoding. The supported algorithms depend on the curl build, so start with curl --version rather than assuming that Brotli or another codec is available everywhere.
When --compressed saves decoded content, dumped response headers remain unchanged. You may therefore have a plain-text file beside a header file that still says Content-Encoding: gzip and gives the length of the coded representation. Decompressing that file again is a mistake. Record the curl options with the files so a later reader knows which processing already happened.
The commands below use separate output names. Run them in a fresh directory and replace the example URL with an endpoint you are authorized to inspect. Keep the method, path, authentication and other request headers consistent across comparisons. A response that differs because you reached a login page is not evidence about gzip behavior.
curl --version
curl --silent --show-error --max-time 15 \
-H "Accept-Encoding: identity" -D identity.headers \
-o identity.body https://example.com/resource
curl --silent --show-error --max-time 15 \
-H "Accept-Encoding: gzip" -D coded.headers \
-o coded.body https://example.com/resource
curl --silent --show-error --max-time 15 --compressed \
-H "Accept-Encoding: gzip" -D decoded.headers \
-o decoded.body https://example.com/resourceSource: curl manual: compressed responses, headers and output behavior ↗
Treat Accept-Encoding as negotiation
Accept-Encoding communicates which response codings the client accepts and their preferences. It does not force the server to compress every response. A server may choose an acceptable uncoded representation. Its behavior can also depend on resource type, size, configuration and intermediaries; measure your own endpoint rather than assuming a universal compression threshold.
A quality value of zero excludes the associated coding. Do not decide that gzip is acceptable by searching the header for the substring gzip: that incorrectly accepts gzip;q=0. Correct negotiation must account for the complete field semantics, including wildcard and identity rules. Use a maintained server implementation instead of extending a short diagnostic fixture into a production negotiation parser.
For a baseline comparison, explicitly ask for identity and then for gzip. Preserve the actual request and response headers. If a proxy rewrites Accept-Encoding, your command alone does not establish what the origin received. Compare approved gateway or origin observations before concluding that the application ignored the client.
Source: RFC 9110: HTTP content coding, negotiation and representation metadata ↗
Use the body and metadata together to classify the failure
A decoding error does not identify the component at fault. Inspect a preserved coded body and its declared codings, then compare observations across the application, proxy and client boundaries. Avoid changing compression at several layers at once; doing so can make a broken response disappear without revealing why it was broken.
If a response has multiple content codings, they describe the sequence applied and must be decoded in reverse order. Two gzip layers accompanied by only one declared layer leave gzip data after one legitimate decoding pass. Conversely, an intermediary that decompresses a body but forwards the old Content-Encoding creates a label that no longer describes the content.
| Observation | Likely mismatch to investigate | Evidence to preserve |
|---|---|---|
| gzip decoding fails | Plain, damaged or truncated bytes labelled gzip | Coded body, status and headers |
| Binary output despite --compressed | Missing Content-Encoding or an extra undeclared layer | Body after client processing |
| Decoded file length differs from Content-Length | Comparing decoded bytes with coded length | curl options and separate headers |
| Only some clients fail | Different negotiation, codec support or cached variants | Actual request headers and client build |
| Origin works, public route fails | Proxy transformation or cache policy | Comparable observations at each hop |
Source: RFC 9110: HTTP content coding, negotiation and representation metadata ↗
Compare lengths at the same representation boundary
When Content-Length describes an ordinary full response with content coding, compare it with the number of coded content bytes, not the number of characters or bytes after decompression. A UTF-8 character count introduces another possible mismatch. Keep headers and body separate instead of counting a combined -i output stream.
If a layer changes the body, its framing and representation metadata must remain consistent. Copying the upstream Content-Length after recompression or decompression can be wrong. Do not repair a length discrepancy by setting an arbitrary larger value. First determine which bytes the field is supposed to describe and which component actually generated them.
For a partial download, unexpected connection closure, or failed decoder, discard the assumption that a saved output file is complete. Preserve the failure and compare it with a clean request. An HTTP status alone does not prove that the subsequent body transfer and decoding succeeded. The lab checks curl exit status as well as the returned body.
Source: RFC 9110: HTTP content coding, negotiation and representation metadata ↗
Distinguish a gzip file from HTTP content coding
An endpoint can intentionally serve a gzip file as its resource. For example, a downloadable archive described as application/gzip need not use Content-Encoding: gzip merely because its file format contains compressed data. Without a declared HTTP content coding, --compressed does not mean extract every archive the user downloads. A saved gzip file can therefore be the correct result rather than a decoding failure.
Compare the expected resource contract before labelling missing Content-Encoding as a defect. In this lab, the intended resource is plain text and the unlabelled path deliberately sends its gzip-coded bytes while retaining text/plain metadata. A genuine compressed-file download has a different purpose. Preserve that distinction in download APIs and tests: an HTTP decoding step and an explicit archive extraction step should have clearly defined owners. Otherwise a client can accidentally remove a layer the caller expected to keep, or preserve a layer the caller expected the HTTP stack to remove.
Source: RFC 9110: HTTP content coding, negotiation and representation metadata ↗
Keep identity and compressed cache variants distinct
When response selection depends on Accept-Encoding, Vary: Accept-Encoding communicates that dependency to caches. The field names request inputs used in selecting a representation; it is not a request to enable gzip. A cached identity response and a cached gzip response must not be confused merely because they share a URL.
Adding Vary is not a complete CDN configuration test. A service can normalize supported encodings or use provider-specific cache rules, and an earlier bad object can remain cached after an origin fix. Inspect the actual cache behavior and the provider configuration. Apply a targeted invalidation through the supported workflow when a confirmed stale representation needs removal.
Keep validators consistent with the selected representation as well. Strong validators identify representation data, so byte-different coded variants need appropriate treatment. Do not reuse a strong tag blindly while transforming the bytes. Conditional requests and range requests introduce additional representation requirements; verify those separately instead of assuming a successful gzip GET covers them.
Reproduce six controlled cases on loopback
Save the following as gzip_lab.py and run python3 gzip_lab.py with Python 3 and a gzip-capable curl on PATH. It creates a temporary header file, binds only to 127.0.0.1 on a system-selected port, bypasses proxies for the loopback requests, and shuts down the server and removes the file afterward. It does not contact public services or modify a running application.
The fixture deliberately accepts only the exact gzip header value for its good path; other values select the plain body. This is enough for the controlled comparisons and is not a general Accept-Encoding implementation. Three other paths deliberately return inconsistent coding metadata so you can distinguish a decoder failure from a successful transfer that still contains gzip bytes.
The script was executed with Python 3.12.14 and curl 8.5.0: all 21 checks passed across six HTTP requests. It confirms exact coded and decoded bytes, declared lengths, unchanged dumped headers, emitted Vary, and the three faulty responses. It does not test a real cache, TLS, Brotli, HTTP/2, HTTP/3, streaming compression or every form of corrupted gzip.
import gzip
import subprocess
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
PLAIN = ('compression fixture: predictable text\n' * 40).encode('utf-8')
CODED = gzip.compress(PLAIN, mtime=0)
DOUBLE = gzip.compress(CODED, mtime=0)
class Handler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, *args):
pass
def do_GET(self):
# Deliberately restricted fixture, not a general Accept-Encoding parser.
if self.path == '/good':
coded = self.headers.get('Accept-Encoding') == 'gzip'
body, encoding = (CODED, 'gzip') if coded else (PLAIN, None)
elif self.path == '/wrong-label':
body, encoding = PLAIN, 'gzip' # Intentionally broken metadata.
elif self.path == '/unlabelled':
body, encoding = CODED, None # Intentionally missing metadata.
elif self.path == '/double':
body, encoding = DOUBLE, 'gzip' # Only one of two layers declared.
else:
self.send_error(404)
return
self.send_response(200)
self.send_header('Content-Type', 'text/plain; charset=utf-8')
self.send_header('Vary', 'Accept-Encoding')
if encoding:
self.send_header('Content-Encoding', encoding)
self.send_header('Content-Length', str(len(body)))
self.send_header('Connection', 'close')
self.end_headers()
self.wfile.write(body)
checks = 0
def check(value):
global checks
assert value
checks += 1
with tempfile.TemporaryDirectory(prefix='pwp-gzip-') as directory:
root = Path(directory)
server = HTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=server.serve_forever,
kwargs={'poll_interval': 0.05})
thread.start()
try:
url = f'http://127.0.0.1:{server.server_port}'
def request(path, *options):
headers = root / 'headers.txt'
result = subprocess.run(
['curl', '-q', '--silent', '--show-error', '--noproxy', '*',
'--http1.1', '--max-time', '5', '--dump-header', str(headers),
*options, url + path], capture_output=True, timeout=8)
fields = {}
for line in headers.read_text().splitlines():
if ':' in line:
name, value = line.split(':', 1)
fields[name.lower()] = value.strip()
return result, fields
identity, ih = request('/good', '-H', 'Accept-Encoding: identity')
check(identity.returncode == 0 and identity.stdout == PLAIN)
check('content-encoding' not in ih)
check(int(ih['content-length']) == len(PLAIN))
coded, ch = request('/good', '-H', 'Accept-Encoding: gzip')
check(coded.returncode == 0 and coded.stdout == CODED)
check(ch['content-encoding'] == 'gzip')
check(int(ch['content-length']) == len(coded.stdout))
check(gzip.decompress(coded.stdout) == PLAIN)
decoded, dh = request('/good', '--compressed', '-H', 'Accept-Encoding: gzip')
check(decoded.returncode == 0 and decoded.stdout == PLAIN)
check(dh['content-encoding'] == 'gzip') # Dumped headers stay unchanged.
check(int(dh['content-length']) == len(CODED))
check(len(decoded.stdout) != int(dh['content-length']))
check(ih['vary'] == ch['vary'] == dh['vary'] == 'Accept-Encoding')
wrong, wh = request('/wrong-label', '--compressed', '-H', 'Accept-Encoding: gzip')
check(wrong.returncode != 0) # Do not assert backend-specific error wording.
check(wh['content-encoding'] == 'gzip')
unlabelled, uh = request('/unlabelled', '--compressed', '-H', 'Accept-Encoding: gzip')
check(unlabelled.returncode == 0 and unlabelled.stdout == CODED)
check('content-encoding' not in uh)
check(gzip.decompress(unlabelled.stdout) == PLAIN)
doubled, bh = request('/double', '--compressed', '-H', 'Accept-Encoding: gzip')
check(doubled.returncode == 0 and doubled.stdout == CODED)
check(bh['content-encoding'] == 'gzip')
check(gzip.decompress(doubled.stdout) == PLAIN)
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
check(not thread.is_alive())
print(f'{checks} checks passed across six local HTTP requests.')Source: Python gzip: compression and decompression helpers ↗
Follow one response through the real delivery path
Start with an authorized read-only GET that reproduces the symptom. Record the client build, request headers, status, response headers, exit status and saved-body processing. Compare identity and gzip requests while keeping other inputs constant. Use GET rather than assuming a HEAD request reproduces body transformation behavior.
Next compare the public route with an authorized origin or staging observation that preserves the intended hostname and TLS verification. Directing a request to an IP can change routing and certificate checks, so do not remove verification just to make the comparison easy. Inspect the responsible proxy or application logs for evidence of decompression, recompression or header rewriting.
After fixing the identified layer, repeat both positive and negative cases. A correct identity response, a correctly decoded gzip response and consistent cache selection answer different questions. Keep the smallest regression fixture that reproduces the original defect. Fixing metadata and transformation ownership is more durable than asking every client to guess which decoding pass is missing.
Source: curl manual: compressed responses, headers and output behavior ↗
Your next steps
- Record what the client accepted, what the server declared and which bytes the tool saved.
- Use --compressed deliberately; dumped response headers can still describe the coded representation.
- Verify transformation metadata and cache variants independently, then repeat the original failing request.
Sources & official resources
Linked resources checked on 2026-10-29. 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 →