Free, independent guides since 2010

Security & privacy

HTTP security headers: a practical guide

Which HTTP security headers to set and why: HSTS, Content-Security-Policy, X-Content-Type-Options, Referrer-Policy, Permissions-Policy and frame protection – with examples for Apache, Nginx and Cloudflare.

<guide section="Security & privacy" type="article" read="1 min"/>

With a few lines of server configuration, you can switch on browser protections against clickjacking, content sniffing, leaking URLs and injected scripts. This website itself sends a full set via a Cloudflare _headers file.

The essential headers

HeaderProtects againstTypical value
Strict-Transport-SecurityDowngrade to HTTPmax-age=31536000; includeSubDomains
X-Content-Type-OptionsMIME sniffingnosniff
Referrer-PolicyLeaking full URLs to other sitesstrict-origin-when-cross-origin
Content-Security-PolicyInjected scripts (XSS), clickjackingSite-specific
Permissions-PolicyUnwanted access to camera, microphone, locationcamera=(), microphone=(), geolocation=()
X-Frame-Options (legacy)ClickjackingSAMEORIGIN

Examples

Plain text
# Apache (.htaccess)
<IfModule mod_headers.c>
  Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
  Header set X-Content-Type-Options "nosniff"
  Header set Referrer-Policy "strict-origin-when-cross-origin"
  Header set Permissions-Policy "camera=(), microphone=(), geolocation=()"
</IfModule>

# Nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;

# Cloudflare static assets (_headers file)
/*
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin

More on Apache configuration in .htaccess basics.

Content-Security-Policy step by step

  1. List every source your pages load: scripts, styles, fonts, images, embeds.
  2. Start with Content-Security-Policy-Report-Only and watch the browser console.
  3. Tighten until nothing legitimate is blocked.
  4. Switch to the enforcing header.
Plain text
Content-Security-Policy: default-src 'self'; img-src 'self' data:; frame-src https://www.youtube-nocookie.com; frame-ancestors 'self'; base-uri 'self'; form-action 'self'

Frequently asked questions

Can security headers break my site?

A strict Content-Security-Policy can block scripts, fonts or embeds you rely on. Test it in report-only mode first. The other basic headers rarely cause problems.

Do security headers help SEO?

Not directly. They protect visitors and your reputation, and HTTPS (which HSTS enforces) is a lightweight ranking signal.