HTTP, TLS & Web Performance

HTTP Headers Every Site Owner Should Know

A practical tour of the response headers that control caching, security, content types and indexing, with safe starting values.

Key takeaways

  • Content-Type and Cache-Control have the biggest everyday effect on whether pages display correctly and load quickly.
  • Strict-Transport-Security, Content-Security-Policy and X-Content-Type-Options are core browser-side protections.
  • Headers can come from several layers, so verify the final response a visitor actually receives.
  • Strict policies are best introduced gradually, because a wrong value can lock visitors out of features or the whole site.

Response headers are short instructions your server sends along with every page and file. They tell browsers how long to keep a copy, how to interpret the bytes, whether to insist on encryption, who may embed the page and what search engines may do with it. A handful of them cover most of what a site owner needs.

You usually set them in your web server configuration, your hosting control panel, your content delivery network or your application code. Check what your site sends today before changing anything.

Look before you change

From a terminal on macOS, Linux or Windows (curl.exe in Windows PowerShell 5.1):

curl -sI https://www.example.com/

-I sends a HEAD request. A few servers answer HEAD differently from GET, so if something looks odd, fetch normally and print the headers:

curl -s -D - -o /dev/null https://www.example.com/

On Windows, replace /dev/null with NUL. In a browser, the Network tab of developer tools shows the same information per request. Check the home page, an inner page, a stylesheet, an image and an error page, since different rules often apply to each.

What response headers control
Your response Headers travel with every page and file. Indexing What search engines may list. Privacy What is shared with other sites. Content rules What a page may load or run. Format How to read the bytes. Caching How long copies may be reused. Transport Whether HTTPS is required. Your response Headers travel with every page and file. Format How to read the bytes. Caching How long copies may be reused. Transport Whether HTTPS is required. Content rules What a page may load or run. Privacy What is shared with other sites. Indexing What search engines may list.

Content-Type: say what you are sending

Content-Type names the media type, and for text it should name the character set too.

Content-Type: text/html; charset=utf-8

A missing or wrong value produces familiar symptoms: accented characters turning into nonsense, a stylesheet that is ignored, a file that downloads when it should display.

Pair it with X-Content-Type-Options: nosniff, which tells the browser to trust your declared type and not guess from the content. Guessing has historically allowed an uploaded file to be treated as a script.

For downloads, Content-Disposition: attachment; filename="report.pdf" asks the browser to save the file under that name.

Cache-Control: decide what may be reused

Cache-Control is the main caching instruction. Common patterns:

Content Value Effect
Versioned files such as app.3f9a.css max-age=31536000, immutable Keep for a year without rechecking
HTML pages no-cache Store, but revalidate before each use
Account pages and private data no-store Do not keep a copy
Personalized but cacheable private, max-age=60 Browser only, not shared caches
Public pages behind a CDN public, max-age=60, s-maxage=600 Shared caches may hold longer

Note the naming trap: no-cache permits storing and requires checking with the server first. no-store is the one that forbids keeping a copy.

Add validators so rechecks are cheap. With ETag or Last-Modified present, an unchanged file can be answered with a short 304 Not Modified. More in browser caching, and you can experiment with the cache freshness simulator.

Vary and Content-Encoding

Compression shrinks text dramatically. The server marks it with Content-Encoding: gzip or br (Brotli). Because the response then depends on what the client said it accepts, it should also send Vary: Accept-Encoding, which tells caches to keep separate versions. Details are in compression with gzip and Brotli.

Be sparing with Vary. Listing something that differs for nearly every visitor, such as User-Agent, makes shared caching close to useless.

Strict-Transport-Security: insist on HTTPS

Strict-Transport-Security: max-age=31536000; includeSubDomains

After seeing this over HTTPS, a browser refuses to use plain HTTP for your site for the stated number of seconds, and does not let visitors click past certificate errors.

That strength is also the risk. Start with a short max-age such as 300, confirm every subdomain works over HTTPS before adding includeSubDomains, and treat the preload list as close to permanent. Read the HSTS guide first.

Content-Security-Policy: limit what a page can do

A Content Security Policy lists where scripts, styles, images and frames may come from. If an attacker manages to inject markup, a good policy can stop it from running.

Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.com; object-src 'none'; frame-ancestors 'self'

Real sites rarely get this right on the first try, because analytics, fonts and embedded widgets all need allowances. Use Content-Security-Policy-Report-Only first: the browser reports what would have been blocked without blocking it. Content Security Policy in practice goes further.

The frame-ancestors directive controls who may put your page in a frame, which defends against clickjacking, where a hidden frame tricks people into clicking. The older X-Frame-Options: DENY or SAMEORIGIN does a simpler version and is still often sent alongside.

Privacy and feature controls

Referrer-Policy decides how much of your page address other sites see when a visitor follows a link or your page loads an outside file. strict-origin-when-cross-origin sends the full address within your site, only the origin to other HTTPS sites, and nothing on a downgrade to HTTP. It is the common browser default, but setting it states your intent.

Permissions-Policy switches off browser features you do not use:

Permissions-Policy: camera=(), microphone=(), geolocation=()

Cross-origin sharing is governed by the Access-Control-Allow-Origin family. Only send these where another site genuinely needs to read your responses; see CORS explained.

Cookies

Session cookies deserve protective attributes:

Set-Cookie: session=abc123; Path=/; Secure; HttpOnly; SameSite=Lax

Secure limits the cookie to HTTPS, HttpOnly hides it from page scripts and SameSite restricts cross-site sending. Paste one into the Set-Cookie explainer to see each attribute spelled out.

Redirects, errors and search engines

Location carries the destination of a redirect, and the status code beside it signals whether the move is permanent. Retry-After accompanies 429 and 503 responses to say when to come back.

X-Robots-Tag gives search crawlers instructions for any file type, including PDFs that cannot hold an HTML tag:

X-Robots-Tag: noindex

A stray noindex copied from a staging server to production can remove pages from search results, so check for it after launches. A crawler must be allowed to fetch the page in order to see the header.

Headers you may want to remove or ignore

Server and X-Powered-By often announce software names and versions. Trimming them does not fix any weakness, but there is little reason to volunteer the detail. X-XSS-Protection belongs to a browser filter that modern browsers have removed; relying on it achieves nothing. Expires and Pragma are older caching mechanisms that Cache-Control supersedes.

Where to set headers

The right place depends on how your site is run. Here are two common web servers, each adding a security header.

In nginx, inside a server or location block:

add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

The word always makes nginx include the header on error responses too. Be aware that add_header lines in an inner block replace the ones inherited from the outer block, so a single addition in a location can silently drop your other headers there.

In Apache, with the headers module enabled:

Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"

This can go in the virtual host configuration, or in .htaccess if your host permits it. Test the configuration before reloading: nginx -t for nginx, apachectl configtest for Apache.

On managed hosting or a static site service, look for a headers or rules screen, or a configuration file the service documents. A content delivery network can usually add, change or remove headers in its own rules, which is convenient but easy to forget when you later debug the origin.

Request headers worth logging

Site owners mostly set response headers, but a few incoming ones help with diagnosis. Host shows which name the visitor used. User-Agent hints at the browser or bot, though anyone can forge it. Referer shows where a visit came from, within the limits of the other site's referrer policy.

Behind a proxy or CDN, your server sees the proxy's address as the client. The original address is passed in X-Forwarded-For, in the standardized Forwarded header or in a vendor's own header. Trust these only when the request really came from your proxy. Otherwise a visitor can type in any address they like and slip past address-based limits or pollute your logs.

Rolling out changes safely

A safe way to introduce a new header
1 Record Save the current headers for several page types. 2 Test Apply the change on a staging copy first. 3 Report only Use report mode or a short duration where possible. 4 Release Deploy and check the live response yourself. 5 Tighten Raise durations and strictness once logs stay quiet. Record Save the current headers for several page types. 1 Test Apply the change on a staging copy first. 2 Report only Use report mode or a short duration where possible. 3 Release Deploy and check the live response yourself. 4 Tighten Raise durations and strictness once logs stay quiet. 5

Watch for duplicates. If both your application and your proxy add Cache-Control or a security policy, the combined result may not be what either intended. Pick one layer to own each header.

Also test failure pages. Some server configurations attach custom headers only to successful responses unless told otherwise, so your 404 and 500 pages may be missing protections.

A sensible starting set

For an ordinary HTTPS content site, a reasonable first pass is:

  1. Correct Content-Type with charset=utf-8 on text.
  2. X-Content-Type-Options: nosniff.
  3. A caching rule for each kind of content.
  4. Referrer-Policy: strict-origin-when-cross-origin.
  5. frame-ancestors 'self' in a Content Security Policy.
  6. Strict-Transport-Security with a short duration, lengthened later.
  7. Protective cookie attributes.

Revisit the list whenever you add a third-party service, change hosts or put a new proxy in front of the site, since any of those can change what visitors receive.

Headers are one layer. They do not replace software updates, input validation or access checks, and a perfect score from a header scanner does not mean a site is secure. They are inexpensive, though, and most take effect the moment you send them.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic