HTTP headers

suggest change

HTTP headers are name/value pairs sent with every request and response. They carry metadata: the type of the body (Content-Type), authentication (Authorization), caching rules (Cache-Control, ETag), cookies (Cookie, Set-Cookie), and much more.

Two rules matter in practice:

This article shows how to send and read headers with Ruby's standard library Net::HTTP and how to work with them on the server side in a Rack application.

Sending request headers with Net::HTTP

The simplest way is to pass a hash of headers to Net::HTTP.get or Net::HTTP.get_response (supported since Ruby 3.0):

require 'net/http'

uri = URI('https://httpbin.org/headers')
body = Net::HTTP.get(uri, { 'User-Agent' => 'MyApp/1.0', 'Accept' => 'application/json' })
puts body

For more control, build a request object. Net::HTTP::Get, Net::HTTP::Post etc. accept an initial headers hash, and headers can also be set with []=:

require 'net/http'
require 'json'
require 'securerandom'

uri = URI('https://httpbin.org/post')

req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req['Authorization'] = "Bearer #{ENV.fetch('API_TOKEN', 'secret')}"
req['Accept'] = 'application/json'
req['X-Request-Id'] = SecureRandom.uuid
req.body = JSON.generate(name: 'Alice')

res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
  http.request(req)
end
puts res.code

Useful methods on a request (they come from the Net::HTTPHeader module, shared by requests and responses):

Method What it does
req['Name'] = value set a header, replacing previous values
req.add_field('Name', value) add another value for a header (allows duplicates)
req.delete('Name') remove a header
req.key?('Name') check if a header is set (case-insensitive)
req.basic_auth(user, pass) set Authorization: Basic ...
req.content_type = 'text/plain' set Content-Type
req.set_range(0, 100) set Range: bytes=0-99 (start, length)
require 'net/http'

req = Net::HTTP::Get.new(URI('https://example.com/'))
req.add_field('Accept-Language', 'en')
req.add_field('Accept-Language', 'pl;q=0.8')
req.basic_auth('user', 'pa55')

p req.get_fields('accept-language') # => ["en", "pl;q=0.8"]
p req['Authorization']              # => "Basic dXNlcjpwYTU1"

Note that Net::HTTP adds some headers on its own: Accept-Encoding (gzip/deflate; the response body is transparently decompressed), Accept: */*, User-Agent: Ruby and Host. Setting them yourself overrides the defaults.

Reading response headers

A Net::HTTPResponse also includes Net::HTTPHeader, so headers are accessed with []. Lookup is case-insensitive:

require 'net/http'

res = Net::HTTP.get_response(URI('https://example.com/'))

puts res['Content-Type']   # => "text/html; charset=utf-8"
puts res['content-type']   # same header
puts res.content_type      # => "text/html" (media type only, no parameters)
p res.type_params          # => {"charset" => "utf-8"}
p res.content_length       # => Integer or nil
p res.key?('etag')         # => true or false

[] returns all values of a header joined with ", ". That breaks headers such as Set-Cookie whose values may themselves contain commas (in Expires= dates). Use get_fields to get an array of raw values:

cookies = res.get_fields('set-cookie') || []
cookies.each { |c| puts c.split(';').first }

To iterate over all headers use each_header (names lowercased, repeated values joined with ", ") or to_hash (names lowercased, values are arrays):

res.each_header do |name, value|
  puts "#{name}: #{value}"
end

p res.to_hash
# => {"content-type" => ["text/html; charset=utf-8"], "etag" => ["\"84238dfc\""], ...}

Conditional requests with ETag

Headers enable caching. The server sends an ETag (a version identifier); on the next request the client sends it back in If-None-Match. If the resource didn't change, the server replies 304 Not Modified with an empty body:

require 'net/http'

uri = URI('https://example.com/')

Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
  first = http.request(Net::HTTP::Get.new(uri))
  etag = first['ETag']
  puts "first: #{first.code}, etag: #{etag}"

  req = Net::HTTP::Get.new(uri)
  req['If-None-Match'] = etag if etag
  second = http.request(req)

  case second
  when Net::HTTPNotModified then puts 'not modified, use cached copy'
  when Net::HTTPOK          then puts "changed, #{second.body.bytesize} bytes"
  end
end

Last-Modified / If-Modified-Since work the same way using dates. Use Time#httpdate (from require 'time') to format them: Time.now.httpdate # => "Sat, 17 Oct 2026 12:00:00 GMT".

Headers on the server side with Rack

Every Ruby web framework (Rails, Sinatra, Hanami, Roda) is built on Rack, so the rules below apply to all of them.

Reading request headers

Rack passes request headers in the env hash using CGI-style names: uppercased, - replaced with _, prefixed with HTTP_. So User-Agent becomes env['HTTP_USER_AGENT'] and X-Request-Id becomes env['HTTP_X_REQUEST_ID']. Two exceptions have no prefix: CONTENT_TYPE and CONTENT_LENGTH.

# config.ru
require 'rack'

app = lambda do |env|
  req = Rack::Request.new(env)

  ua         = req.user_agent                # env['HTTP_USER_AGENT']
  ctype      = req.content_type              # env['CONTENT_TYPE']
  request_id = req.get_header('HTTP_X_REQUEST_ID')
  auth       = env['HTTP_AUTHORIZATION']

  body = "UA: #{ua}\nContent-Type: #{ctype}\nRequest-Id: #{request_id}\nAuth: #{auth ? 'yes' : 'no'}\n"
  [200, { 'content-type' => 'text/plain' }, [body]]
end

run app

Run it with rackup (gem install rack rackup puma) and test with curl:

curl -H 'X-Request-Id: abc' http://localhost:9292/

Setting response headers

The second element of a Rack response is the headers hash. Since Rack 3, response header names must be lowercase; mixed-case names like Content-Type are rejected by Rack::Lint. Rack::Response and Rack::Headers handle this for you by downcasing names:

require 'rack'
require 'time'

app = lambda do |env|
  res = Rack::Response.new
  res.content_type = 'application/json'
  res['Cache-Control'] = 'public, max-age=60'      # stored as "cache-control"
  res['Last-Modified'] = Time.utc(2026, 1, 1).httpdate
  res.set_cookie('session', value: 'abc123', httponly: true, secure: true, same_site: :lax)
  res.set_cookie('theme', value: 'dark', path: '/')
  res.write('{"ok":true}')
  res.finish # => [200, headers, body]
end

Multiple values for one header (e.g. two cookies) are stored as an array in Rack 3, and the server writes each one as a separate header line.

Conditional GET in Rack

Rack::ETag computes an ETag from the body and Rack::ConditionalGet returns 304 Not Modified when the client's If-None-Match or If-Modified-Since matches:

# config.ru
require 'rack'

use Rack::ConditionalGet
use Rack::ETag

run ->(env) { [200, { 'content-type' => 'text/plain' }, ["Hello\n"]] }

Common headers reference

Header Direction Purpose
Content-Type both media type of the body, e.g. application/json
Content-Length both size of the body in bytes
Accept request media types the client accepts
Authorization request credentials, e.g. Bearer <token>
User-Agent request identifies the client
Cookie / Set-Cookie request / response cookies
Cache-Control both caching rules
ETag / If-None-Match response / request validation-based caching
Location response target of a redirect or newly created resource
Retry-After response how long to wait after 429 or 503

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents