Skip to main content
Tech Tutorials & Programming

Aug 28, 2026

How Do You Use cURL With Headers?

Learn how to add curl headers, send request bodies, inspect traffic, protect credentials, manage redirects, and troubleshoot authentication.

How Do You Use cURL With Headers?

Quick Answer

Use curl's -H or --header option to send a Hypertext Transfer Protocol (HTTP) request header. Repeat the option for multiple fields, and use --json for JavaScript Object Notation (JSON) bodies. Inspect traffic with -v, -i, -I, or -D, keep credentials out of saved commands, and review custom fields before redirects.

bash

Key Takeaways

  • Add one field: Pass one quoted Name: value argument to -H or --header.
  • Send several fields: Repeat the header option once for every distinct field.
  • Match the body: Use Content-Type for request content and Accept for response preferences.
  • Protect credentials: Inject secrets at runtime, require encrypted transport, and redact diagnostic output.
  • Inspect the correct direction: Use -v for sent fields and -i, -I, or -D for received fields.
  • Review redirects: Custom secrets can follow redirects beyond their intended origin.
  • Separate proxy metadata: Use --proxy-header for an HTTP proxy and --header for the destination.

Which curl Header Option Should You Use?

curl uses -H for request headers, -i or -D for responses, -I for HEAD, and -v for controlled connection troubleshooting. Each option answers a different transfer question, and choosing by output direction prevents misleading tests.

Taskcurl optionWhat happensBest for
Add or replace a request field-H or --headerSends the supplied field to the destinationApplication requests
Show response fields with content-i or --show-headersWrites fields and content togetherQuick inspection
Request HEAD metadata-I or --headChanges the method to HEADMetadata checks
Save received fields separately-D FILE or --dump-header FILEWrites received header blocks to a fileScripts and audits
Inspect both directions-v or --verboseShows request, response, and connection detailsControlled debugging

Choose -i when response content matters. Use -D when another program must parse fields separately. The -I option is different because it changes the request method.

--show-headers is the current long name for -i, while the older --include name remains an alias. Reserve -v for diagnostics because it also exposes connection details.

curl parses options across the current operation, even when options appear after a destination. Placing options first makes commands easier to review. Use --next when later destinations need a separate local option set.

What Should You Check Before Adding curl Headers?

curl header commands require the native binary, a documented endpoint, correct shell syntax, and the destination's field rules. Confirm those inputs before sending content or credentials. A short prerequisite check prevents most copied-command failures.

Complete these checks in order:

  1. Confirm the executable: Run the native curl binary from a terminal whose command aliases you understand.
  2. Check the version: Verify that every option used by the command exists in the installed build.
  3. Read the endpoint documentation: Record the Uniform Resource Locator (URL), method, fields, body format, and authentication scheme from its Application Programming Interface (API) documentation.
  4. Match the shell: Use quoting and line continuations that fit Bash, zsh, or PowerShell.

Several useful options arrived in different curl releases. Record a minimum version beside dependent scripts. Pin the same build across development, testing, and production when consistent behavior matters.

FeatureMinimum curl versionCompatibility note
--json7.82.0Older builds need explicit fields and --data-binary
--rate7.84.0Controls transfer starts for multiple destinations
Variables and expandable options8.3.0Required for --variable and --expand-header
--show-headers8.10.0--include remains a working alias

The curl command-line manual documents these release boundaries. Run curl --version before using a copied command. Its output also lists protocols, libraries, and compiled features.

Windows PowerShell 5.1 defines curl as an Invoke-WebRequest alias. PowerShell 7 does not define that alias. Call curl.exe when the native curl command is required.

bash

The remaining examples use Bash and zsh unless their code fence says otherwise. Replace every reserved example address with an approved destination. Never publish live credentials inside a copied command.

What Are HTTP Headers in curl?

HTTP headers are named fields carrying request metadata, credentials, representation preferences, conditions, and routing information. Header fields travel separately from message content, and servers interpret each field according to its defined semantics.

Request for Comments (RFC) 9110 was published in 2022. The standard defines HTTP semantics and case-insensitive field names. Field values follow rules defined for that specific name.

HeaderRequest purposeExample value
AcceptStates preferred response media typesapplication/json
Content-TypeDescribes the request body's media typeapplication/json
AuthorizationCarries destination credentialsBearer TOKEN
User-AgentIdentifies the requesting clientinventory-client/1.0
If-None-MatchMakes retrieval conditional on an entity tag"abc123"

curl accepts custom fields in Name: value form. The conventional space after the colon is optional. Leave carriage returns and newlines out because curl adds the required line ending.

Duplicate names need field-specific handling. Content-Type is a singleton field and should not appear twice. List-based fields can permit several comma-separated members, but their definitions control valid combinations.

Content-Type describes existing request-body bytes. The field does not convert plain text into JSON. Accept expresses response preferences, while the server selects a supported representation.

Correct fields cannot repair a wrong method, malformed body, expired credential, or unsupported endpoint. Treat the destination documentation as the authority. Test unfamiliar fields against one controlled request before automation begins.

How Do You Add One Header With curl?

curl adds one request header when -H or --header receives a quoted Name: value argument for the current transfer operation. Put options before the destination for readability. The parser still recognizes them elsewhere in the same operation.

The following GET requests a JSON response without sending a body. Accept describes the preferred response format.

bash

Quote the complete field so shell spaces remain inside one argument. Single quotes preserve literals in Bash and zsh. Double quotes allow shell variables to expand.

Header values can contain additional colons after the first separator. The destination still determines whether spaces and encoded characters are valid.

A custom field replaces an internally generated field with the same name. An unfamiliar name joins curl's defaults. Check the final request before assuming which defaults remain.

Headers do not change the request method. Use --request only when another selected option does not establish the required method. Unnecessary method overrides can produce incorrect behavior after redirects.

Most local options affect every destination before --next, including authentication exchanges and followed redirects. Review that scope carefully before attaching secrets.

Start with a harmless field and inspect one controlled transfer. Add authentication only after the destination, method, and basic syntax are correct. The sequence keeps connection errors separate from field errors.

How Do You Send Multiple Headers With curl?

curl sends multiple request headers when you repeat -H or --header for every distinct field required by the destination endpoint. Keep each field in its own quoted argument. Separate arguments make reviews and changes easier.

The next request asks for JSON, identifies a client version, and makes the GET conditional. Each field has one option occurrence.

bash

curl expects one complete field per option, not several lines inside one quoted argument. Embedded line breaks can create malformed or dangerous requests.

Repeating the option differs from repeating one field name because several distinct names are ordinary. Follow the field's defined list syntax when one name legitimately carries several values.

Avoid copying an entire browser request into a command. Stale cookies, unsupported encodings, and cache-specific fields can change the response. Begin with documented requirements, then add one field at a time.

Keep stable public fields in a reviewed template. Generate temporary credentials and request identifiers only for the operation that needs them. Separate templates by origin when several services use similar field names.

Signature schemes can depend on canonical names, values, and ordering rules. Follow the destination's signing procedure exactly. A verbose display alone does not prove the server canonicalized the request identically.

How Do You Send JSON With curl Headers?

curl sends JSON with --json, which adds matching Content-Type and Accept fields unless the command overrides them during request creation. The option also supplies request data, so curl selects POST unless another option changes the method.

--json uses --data-binary behavior internally, but it does not validate JSON syntax. The destination still decides whether the content matches its schema. An explicit -X POST merely restates the selected method, so omit it.

bash

Content-Type describes the outgoing representation. Accept states the client's preferred response media types. A JSON request does not guarantee a JSON response, so validate the returned media type.

Override an automatic field only when the endpoint documents another value. curl uses that value, but the body must still match its declared media type.

Use a file when another process already created and validated the body. Prefix the filename with @ so curl reads its contents.

bash

Older builds can send the same bytes with explicit fields and --data-binary. The --data-binary option preserves line endings and other file bytes.

bash

Validate payload.json before starting the transfer. Declaring JSON cannot make malformed or incompatible content valid. Use --json @- only when the producing process closes standard input correctly.

An HTTP 415 response often indicates an unsupported media type or content coding. A malformed JSON document may instead produce 400 or an application-specific error.

How Do You Send Authorization Headers Safely?

curl sends bearer tokens through Authorization, but credentials should enter the process through protected runtime injection. Literal tokens can enter scripts, shell history, logs, and process arguments. Keep saved examples free from working secrets.

curl variables allow the program to import an existing environment value. The command fails when API_TOKEN is absent.

bash

Expansion happens inside curl, so the token is absent from the original process arguments. The environment still needs operating-system and deployment protections. Remove inherited secrets from child processes that do not need them.

Authenticated requests should use Hypertext Transfer Protocol Secure (HTTPS). Transport Layer Security (TLS) encrypts the request in transit. Normal certificate verification also checks the intended server's identity.

When a destination requires HTTP Basic authentication, combine --basic with --user. Supplying only the username lets curl request the password interactively.

bash

Use --anyauth --user only when the destination does not prescribe one supported scheme. Automatic selection sends an initial request and can add a round trip. Automatic selection can also require upload data to be rewound and resent.

Avoid automatic selection for standard-input uploads because curl cannot rewind that stream. Redact authorization fields, cookies, keys, and signatures from retained diagnostics. Give each credential the minimum origin, permissions, and lifetime.

How Do You Remove a Header or Send an Empty Value?

curl suppresses a generated header with Name: and transmits an explicitly empty header with Name; for the current transfer operation. The two forms look similar but create different messages. Choose the form required by documented server behavior.

The first command removes User-Agent. The second sends an empty X-Optional field.

bash

The official curl header guide documents the colon-and-semicolon distinction. A colon suppresses curl's generated field. A semicolon requests a zero-length value.

An absent field has no request entry. An empty field remains present without a value. Gateways and applications can handle those states differently.

Removing Host can make routing fail. Removing Content-Type can break content whose media type must be declared. Suppress a generated field only for a specific operational reason.

Other options can add related fields when they change request framing. Inspect the final request after combining removal with body or authentication options.

Test absence and emptiness separately against one approved endpoint. Use controlled verbose output to confirm the logical outgoing field set. Compare the response status and content before preserving the change.

Intermediaries can still normalize or reject unusual fields. Record why the override exists and which endpoint requires it. That note prevents a later maintainer from restoring a harmful default.

How Do You Load curl Headers From a File?

curl loads request headers from a file when --header receives @filename, using one complete field on each nonblank file line. File-based fields suit reviewed, reusable public values. Header files should not become unprotected secret stores.

A basic headers.txt file can contain the following entries:

bash

Pass the file before the destination. curl reads every valid line as one custom field.

bash

A header file differs from a curl configuration file. The first stores raw fields. The second stores curl options and arguments.

Create separate files for separate origins. That organization reduces accidental delivery of service-specific fields to another destination. File separation does not replace a review of the final command.

Keep bearer tokens, cookies, and API keys out of committed header files. On Linux and macOS, chmod 600 headers.txt limits ordinary access to the owner. Windows deployments should apply an equivalent access control list.

Keep non-secret templates small enough for direct review and store them under version control. Replace generated files atomically so scheduled jobs never read a partial field set.

--header @- reads fields from standard input. Validate generated names, separators, values, and origin scope before curl receives them. Reject carriage returns, newline injection, blank names, and malformed separators.

One process cannot supply two independent streams through the same standard input. Avoid --header @- when the request body also reads from standard input.

How Do You Inspect curl Request and Response Headers?

curl -v displays request and response fields, while -i, -D, and -I provide narrower response-focused views for different troubleshooting tasks. The -I option changes the method to HEAD, so use it only when the endpoint's HEAD behavior is relevant.

Inspection goalOptionImportant behavior
See sent and received fields-vWrites diagnostics to standard error
Show response fields with content-iKeeps fields and content in one stream
Request HEAD metadata-IChanges the HTTP method to HEAD
Save response fields separately-D FILEKeeps header blocks outside the content file

Verbose mode prefixes sent fields with > and received fields with <. Connection details begin with *. Use verbose output only in a controlled environment.

bash

Choose --dump-header when software must parse response fields separately. Store the response content in another file to keep both outputs unambiguous.

bash

The article on showing response headers with curl compares these output modes. A normal GET with -D is more representative than an assumed HEAD equivalent. Some services implement HEAD differently.

Use --silent --show-error when automation needs clean output without hiding transfer errors. Keep diagnostics on standard error and parsed content on standard output.

Preserve the order of response header blocks produced by followed redirects. Redact authorization values, cookies, hostnames, and session identifiers before sharing captured output.

How Do Redirects Change curl Header Handling?

curl can resend custom headers across redirects, so every followed location needs review before sensitive fields are attached. Custom fields remain part of the operation. curl cannot infer which unfamiliar names contain secrets.

An origin consists of a scheme, hostname, and port. Changing any component creates another origin for credential-handling decisions. The path alone does not create a new origin.

curl withholds Authorization and Cookie on cross-origin redirects by default. --location-trusted permits broader credential reuse. Avoid that option unless every reached origin may receive the credentials.

Other custom secrets can still follow the redirect. A field named X-API-Key does not receive automatic protection. Inspect an unexpected Location value before issuing another approved request.

Resolve relative Location values against the current address before approval. Compare the resulting scheme, hostname, and port with the allowed origin set.

The following command follows only HTTPS redirects and permits five redirects. Its custom request identifier contains no secret.

bash

Redirect status also affects the next method. curl normally converts POST to GET after 301, 302, or 303. Responses 307 and 308 preserve the method and content.

Confirm that every destination expects the resulting method, body, and fields. Log redirect statuses without retaining secrets. Store the final effective address beside each accepted result.

How Do Proxy Headers Differ From Destination Headers?

curl keeps destination headers under --header and HTTP proxy headers under --proxy-header, preserving separate recipient boundaries. Proxy authentication also has its own option. Keep destination credentials away from proxy communication.

The example sends one tracing field to the proxy and one media preference to the destination. Every endpoint and credential remains a safe placeholder. The route uses an HTTP proxy for an HTTPS destination.

bash

--proxy-header applies to HTTP proxy communication, including an HTTPS destination's CONNECT setup. SOCKS5 uses its own handshake and carries no HTTP proxy fields. Keep SOCKS5 authentication under --proxy-user when credentials are required.

socks5:// resolves destination names locally. socks5h:// asks the proxy to perform Domain Name System (DNS) resolution. The destination's https:// prefix does not determine either proxy scheme.

Use --user or the documented Authorization scheme for destination credentials. Use --proxy-user for proxy credentials. A destination token cannot resolve a proxy's 407 response.

Using curl with a proxy requires correct schemes, authentication, certificates, and SOCKS5 resolution. Preserve the proxy provider's generated scheme. An HTTPS destination can travel through an HTTP or SOCKS5 proxy.

--proxy-insecure disables HTTPS proxy certificate verification. --insecure disables destination certificate verification. Use either option only during controlled certificate troubleshooting, never as a normal fix.

How Do You Troubleshoot curl Header Errors?

curl header failures usually come from shell quoting, wrong field semantics, expired credentials, redirects, or proxy authentication. Diagnose the observed response before adding fields because extra fields often hide the original problem.

SymptomLikely causeFirst check
HTTP 401Missing, malformed, or expired destination credentialsConfirm the documented authentication scheme
HTTP 403Permission or destination policy rejected the requestRead the response content and destination rules
HTTP 406No available representation matches AcceptReview the requested media types
HTTP 415The body type or content coding is unsupportedCompare the fields with the actual bytes
Literal ${API_TOKEN} arrivesShell quoting prevented expansionReview quotes or use curl variables
HTTP 407HTTP proxy credentials are missing or rejectedCheck --proxy-user and proxy authentication

Use this troubleshooting sequence:

  1. Confirm the request: Verify the destination, method, body format, and documented fields.
  2. Reduce the fields: Keep one required field, then restore the remaining fields individually.
  3. Inspect the transfer: Use --verbose in a controlled environment and compare its direction markers.
  4. Read the complete response: Treat its status, fields, and content as separate diagnostic signals.
  5. Compare the methods: Replace -I with GET when HEAD behavior may differ.

Do not retry an unchanged 401, 403, 407, or 415 response. Correct the underlying authentication, permissions, routing, or content. Repetition cannot repair a deterministic request error.

Some failures occur before HTTP begins. Name-resolution failures, refused connections, and certificate errors require connection diagnostics. Another request field cannot repair those conditions.

Shell behavior can also alter the intended value before curl starts. Print only non-secret test values when checking expansion. Use curl variables when shell interpolation creates avoidable ambiguity.

How Do You Manage curl Headers at Scale?

curl header automation needs per-origin templates, protected secret injection, bounded retries, paced starts, and validated responses. The controls limit one bad field's effect and separate transport failures from invalid results.

Continuous integration and continuous delivery (CI/CD) jobs should keep public fields in reviewed templates. Securing proxy credentials in CI/CD applies the same boundary to automated proxy access. Inject secrets only into the approved job.

The following idempotent GET requests share one curl process. --rate limits their transfer starts.

bash

--rate controls starts for multiple destinations in that process. The option does not govern --parallel, retry delays, or separate workers. Apply per-host limits and jitter in the surrounding scheduler.

Use --retry only for classified transient failures and idempotent operations. --retry-max-time limits when another retry may start. Add --max-time when each transfer attempt also needs a duration limit.

Validate the status, media type, and expected content before accepting a result. Cache safe responses, deduplicate completed work, and classify failures before rescheduling them. Measure cost per valid result rather than raw request volume.

Artificial intelligence (AI) jobs should bind headers, cookies, and proxy sessions for AI agents to one approved task. Sticky routing preserves an exit route, but it does not preserve application cookies automatically. Keep both states aligned when continuity matters.

For automated collection, prefer official APIs when available. Collect permitted data, respect applicable laws and terms, follow target limits, and minimize retained information. One proxy route does not grant permission or remove destination controls.

How Does Proxidize Fit Into curl Header Workflows?

Proxidize supplies the proxy route and session controls, while curl manages destination headers, methods, content, and cookies. The responsibilities remain separate, and changing a destination field does not alter the configured proxy location.

Copy the generated scheme, hostname, port, and credentials from the Proxidize dashboard. Add the destination's documented fields through ordinary curl options.

bash

Current managed products support HTTP, HTTPS, and SOCKS5 access. Standard protocols work with existing curl commands without a custom software development kit. Dashboard and API controls manage access points, usage, and sessions.

Rotating sessions can select another Internet Protocol (IP) exit for independent requests needing route diversity. Sticky sessions retain one exit when linked requests require network continuity.

Residential Proxies suit global, location-sensitive web data workloads. Current controls include country, city, and internet service provider (ISP) targeting. Rotating and sticky sessions support independent or linked requests.

Mobile Proxies suit work that specifically requires mobile network context. Current controls include location targeting, rotating sessions, sticky sessions, dashboard access, and API access. Choose them for a network requirement, not a general trust assumption.

Best For: Residential Proxies suit global data collection that requires broad regional routing.

Best For: Mobile Proxies suit testing or collection that specifically requires a mobile network route.

Proxidize does not remove destination rate limits or field requirements. Test one approved destination and validate its response before increasing volume. Keep curl credentials and proxy session settings under separate operational controls.

What Should You Remember About curl Headers?

Reliable curl header workflows keep request fields, response output, credentials, redirects, and proxy metadata under separate controls. Start with the smallest documented request. Inspect one change at a time before automation.

  • Add one field: Use -H "Name: value" for a documented destination header.
  • Repeat the option: Give every additional field its own -H argument.
  • Describe content accurately: Match Content-Type to the body and use Accept for response preferences.
  • Protect credentials: Inject secrets at runtime, require HTTPS, and redact retained diagnostics.
  • Inspect the correct message: Select -v, -i, -I, or -D according to the required output.
  • Separate recipients: Send destination fields with --header and HTTP proxy fields with --proxy-header.

Frequently asked questions

Pass -H "Header-Name: value" or --header "Header-Name: value" before the destination. Quote the complete field so shell spaces remain inside one argument. When its name matches a field generated by curl, the supplied value replaces that generated field throughout the current operation.

Repeat -H once for every required header, and keep each field inside its own quoted argument. Do not combine several field lines inside one option. Duplicate names are appropriate only when that field's specification permits repeated or comma-combined values for the request.

Send the token through Authorization, but inject its value from an approved runtime source. With a compatible curl build, import API_TOKEN using --variable %API_TOKEN. Expand it through --expand-header "Authorization: Bearer {{API_TOKEN}}", use HTTPS, review redirects, and redact retained diagnostics.

The -i option includes received response headers with normal GET content, while -I sends HEAD and omits the response content. Use -D when software needs GET response headers stored separately from the response body for later automated parsing or inspection.

Use --verbose, or -v, during a controlled local troubleshooting test. Lines beginning with > show sent request fields, while < marks received response fields. Verbose output can expose credentials, cookies, hostnames, and connection details, so redact every retained or shared trace before external distribution.

Ready to launch?

Proxies built for real operations.

For teams that depend on stability, not luck.