Skip to main content

How to Use HTTP Headers for Security and Performance

Configure HTTP security and performance headers with an Nginx example, then verify caching, CSP, HSTS, content types, and compression safely.

i
it.you Editorial Team
November 04, 2026 6 min read
How this article was made: An AI-assisted draft was fact-checked, its cited sources were opened, its examples were reviewed, and the published version was edited under the responsibility of it.you Editorial Team. Read our editorial process.
Browser response headers highlighting cache controls, content security policy, HSTS, and compression

Use HTTP response headers to restrict browser behavior, require HTTPS, control caching, and validate resource versions; deploy them per response type, then test normal and error paths.

Choose headers according to the response

A single header set is rarely correct for an entire application. HTML documents can execute code, authenticated API responses may contain private data, and fingerprinted assets such as app.8f31a2c4.js can be cached for months. Treat each as a separate response class.

Response class Security objective Performance policy
HTML application shell Restrict scripts, framing, features, and referrer data Store only when appropriate and revalidate before reuse
Versioned CSS, JavaScript, fonts, and images Send the correct content type and prevent MIME sniffing Cache for a long period because changing content receives a new URL
Authenticated API response Protect private content and return the correct media type Usually prevent storage with no-store

Cache-Control: no-cache does not mean “do not store.” It permits storage but requires validation before reuse. no-store prohibits compliant caches from storing the response, while private prevents shared-cache storage but can still allow a browser cache. These distinctions are defined in RFC 9111.

Worked scenario: secure a small notes application

Consider a hypothetical application at https://notes.example.test. Its HTML is served from /app/, its fingerprinted bundle is /assets/app.8f31a2c4.js, and /api/account returns the signed-in user’s email address and preferences. The application has no third-party scripts, frames, camera access, or inline JavaScript.

The target behavior is concrete: the HTML must be revalidated, the fingerprinted bundle may be reused for one year, and the account response must not be stored. All responses should require HTTPS, refuse MIME guessing, prevent framing, and limit browser capabilities.

Step 1: classify the routes

  • Use no-cache for /app/ so a browser can keep a copy but must check whether it is current.
  • Use public, max-age=31536000, immutable only for assets whose filename changes whenever their content changes.
  • Use no-store for /api/ because these responses may contain account-specific information.
  • Use Vary: Accept-Encoding when compression changes the representation. A cache uses Vary to keep request-dependent variants separate, as described by MDN’s Vary reference.

Step 2: add the Nginx policy

This example assumes TLS certificates and the upstream application are already configured. Place the map in the Nginx http context:

map $request_uri $notes_cache_control {
    default                         "no-cache";
    ~^/assets/.*\.[0-9a-f]{8}\.    "public, max-age=31536000, immutable";
    ~^/api/                         "no-store";
}

Place these directives inside the existing HTTPS server block:

add_header Cache-Control $notes_cache_control always;
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'" always;

etag on;
gzip on;
gzip_vary on;

location /api/ {
    proxy_hide_header Cache-Control;
    proxy_pass http://notes_backend;
}

The CSP allows only the resources this application actually needs. In particular, frame-ancestors 'none' prevents embedding, and it must be stated explicitly because it does not inherit from default-src, according to the Content Security Policy specification.

Run nginx -t before reloading. If validation succeeds, reload gracefully rather than terminating active connections. Keep the HTTP listener limited to a permanent HTTPS redirect. If you are uncertain which public ports should be reachable through the firewall, compare the deployment with the Common Ports Reference; a typical public web service needs ports 80 and 443, not direct public access to its application upstream.

Step 3: introduce CSP and HSTS cautiously

On an existing site, first change Content-Security-Policy to Content-Security-Policy-Report-Only. Exercise sign-in, navigation, uploads, error pages, and any payment or support integrations. Report-only mode records violations without blocking resources, which is the deployment approach documented by OWASP. Treat reports as untrusted input and avoid retaining full URLs or query strings that may expose tokens or personal data.

Begin HSTS with a short value such as max-age=86400. Increase it only after confirming that HTTPS works reliably. Add includeSubDomains only when every present and future subdomain supports HTTPS. Under RFC 6797, that directive extends the policy to subdomains, and max-age=0 asks browsers to remove a previously stored policy.

Verify the normal, cached, and error paths

Substitute the real staging hostname, then request the application document with compression enabled:

curl --compressed -sS -D - -o /dev/null https://notes.example.test/app/

The significant output should resemble this:

HTTP/2 200
content-type: text/html; charset=utf-8
cache-control: no-cache
content-security-policy: default-src 'self'; script-src 'self'; ...
strict-transport-security: max-age=31536000
x-content-type-options: nosniff
referrer-policy: strict-origin-when-cross-origin
permissions-policy: camera=(), microphone=(), geolocation=()
vary: Accept-Encoding

Next, request the versioned asset:

curl --compressed -sS -D - -o /dev/null \
  https://notes.example.test/assets/app.8f31a2c4.js

Expect Content-Type: text/javascript or another correct JavaScript media type, a long-lived immutable cache policy, and an ETag such as "67f3a9c0-3ad2". Copy the actual validator from your response and send it back:

curl -sS -D - -o /dev/null \
  -H 'If-None-Match: "67f3a9c0-3ad2"' \
  https://notes.example.test/assets/app.8f31a2c4.js

A matching unchanged resource should produce 304 Not Modified without transferring the body. If the validator differs, 200 OK with the new representation is correct. Use the HTTP Status Code Reference when checking redirects, conditional responses, authentication failures, and server errors rather than treating every non-200 response as a failure.

Finally, request an authenticated API route with a non-production test account and verify Cache-Control: no-store. Do not paste a real session cookie into shell history, tickets, or third-party header-checking services. Use a short-lived test credential held in a protected environment or cookie file, then delete it after the test.

Also inspect a deliberate 404 and an application-generated 500 in staging. Because Nginx’s add_header normally applies only to selected status codes, the always parameter is important for consistent error responses; the behavior is documented in the Nginx headers module reference.

Decision boundaries and safer alternatives

  • A strict CSP can break inline scripts, analytics, payment widgets, fonts, or API calls. Inventory dependencies and use report-only mode first. Do not solve violations by broadly adding 'unsafe-inline', 'unsafe-eval', or wildcard origins; use nonces, hashes, or narrow source lists when a dependency is genuinely required.
  • Long HSTS periods and includeSubDomains can make a host inaccessible after a certificate or subdomain mistake. Keep the initial duration short, monitor certificate renewal, and avoid preload submission until the entire domain is intentionally committed to permanent HTTPS.
  • Public caching of personalized responses can expose one user’s data to another through a shared proxy or CDN. Use no-store for sensitive responses, review CDN rules separately, and remember that HTTP cache directives do not control screenshots, browser extensions, malicious clients, or application-managed storage.
  • Long-lived immutable caching is unsafe for stable filenames such as app.js. If content can change at the same URL, use a shorter lifetime with ETag or Last-Modified. Reserve immutable for content-addressed or build-fingerprinted names.
  • Adding a location-level add_header can replace inherited server-level headers in many Nginx versions. Keep related headers together, inspect the effective configuration with nginx -T, and verify real responses rather than assuming inheritance.
  • Headers supplement secure application design; they do not replace output encoding, authorization, CSRF defenses, dependency maintenance, or secure token handling. The Passwords, Hashes, and Tokens guide explains the separate handling required for credentials and session secrets.

Reusable action checklist

  • Inventory HTML, public assets, downloads, APIs, redirects, and error responses.
  • Assign an explicit cache policy to each response class.
  • Give changing assets new fingerprinted URLs before enabling immutable caching.
  • Set accurate Content-Type values and add X-Content-Type-Options: nosniff.
  • Draft CSP from actual dependencies and test it in report-only mode.
  • Deploy HSTS with a short duration before extending its scope or lifetime.
  • Validate server configuration before a graceful reload.
  • Check document, asset, API, redirect, 304, 404, and 500 responses.
  • Test from outside the origin so CDN and reverse-proxy behavior is included.
  • Review reports and logs for secrets, identifiers, and unnecessary retention.
  • Repeat the checks after proxy, framework, CDN, or authentication changes.

Sources and further reading

Continue with the Security guide collection for related explanations reviewed under the same editorial standard.

Related Tools

Complete reference for all HTTP status codes with …

Further reading

Distinguish HTTP 401 from 403 responses, choose the correct status for authentication and authorization failures, and avoid information leaks.