Protection

10 min readUpdated

HSTS: what it is and how to enable the Strict-Transport-Security header safely

Quick answer

HSTS (HTTP Strict Transport Security) is a response header, Strict-Transport-Security, that tells a browser to use only HTTPS for a host for the next max-age seconds. After the first HTTPS visit, the browser rewrites http:// to https:// itself before any request leaves, and it no longer lets users click through certificate errors. Enable it with a short max-age, check every hostname and error page, then raise it step by step to one year. Preload, which also protects the first visit, comes last because removal takes months.

01What is HSTS?

HSTS, short for HTTP Strict Transport Security, is a header a site sends over HTTPS, such as Strict-Transport-Security: max-age=31536000. The browser stores it and, until max-age runs out, loads that host only over HTTPS and treats any certificate error as a hard stop. The standard is RFC 6797.

It closes the gap a redirect leaves open: a plain http:// request from a bookmark, a typed address or an old link travels unencrypted before your server can redirect it, and anyone on the network can answer it instead (OWASP). With the policy stored, that request never leaves. HSTS encrypts nothing itself; TLS does (what is SSL/TLS). The other headers are in the security headers guide, and Content Security Policy has its own page.

Your situationRead next
What the browser does with the headerHow does HSTS work?
nginx sends the header on some responses onlyThree nginx HSTS mistakes, reproduced
Setting it in Apache, Caddy, WordPress, Cloudflare, Kubernetes or Next.jsHow to enable HSTS, per platform
Choosing a max-ageWhat max-age should you use?
Thinking about preloadShould you preload HSTS?
A redirect loop or certificate error since enabling itHSTS, redirect loops and certificate errors

02How does HSTS work?

On the first visit the browser knows nothing about the site. The http:// request goes out in plain text, the server answers 301 to https://, and the HTTPS response carries the header. The browser stores the host with an expiry of now plus max-age, and each later response with the header pushes it forward (MDN).

On later visits the browser checks its list before loading an http:// URL. For a stored host, or a subdomain of one that sent includeSubDomains, it switches to https and port 443 (RFC 6797, section 8.3). Chromium does this as an internal redirect with status 307 and the reason HSTS, shown in developer tools as "307 Internal Redirect": nothing is sent to port 80.

Browsers ignore the header over plain HTTP or in a meta tag and never apply it to IP addresses, and the very first visit stays exposed unless the domain is preloaded (section 14.6).

BrowserSitehttp :80Sitehttps :443First visitGET http://example.com/301 → https://example.com/GET https://example.com/200 + Strict-Transport-Securitystored: HTTPS only for max-ageLater visits307 Internal Redirecthttp:// → https:// in the browsernothing sent to port 80GET https://example.com/200 + header renews the expiry
First visit: http:// gets a 301, and the HTTPS response carries Strict-Transport-Security, which the browser stores. Later visits: the browser switches to https:// itself (shown as 307 Internal Redirect) before any request leaves.

03The Strict-Transport-Security header: directives and values

Directives are separated by semicolons. RFC 6797 tells browsers to ignore a malformed header entirely and, if a response carries several, to use only the first: when a proxy and the application both add one, the first copy wins.

DirectiveMeaningWatch out
max-age=<seconds>Required. How long the browser enforces HTTPS; 31536000 is one yearmax-age=0 deletes the policy, but only over HTTPS
includeSubDomainsCovers every subdomain, present and futureA subdomain without valid HTTPS is unreachable for the whole max-age
preloadAsks for the browsers' preload list; not in RFC 6797Needs max-age of at least 31536000 and includeSubDomains; you still submit the domain at hstspreload.org
Typical values (one header per response)
Strict-Transport-Security: max-age=300                                   # trial
Strict-Transport-Security: max-age=31536000; includeSubDomains           # long-term
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload  # only when preloading

04Three nginx HSTS mistakes, reproduced

Reproduced with nginx 1.22.1 on Debian 12: a plain HTTP test server and two TLS test servers on 127.0.0.1 with a self-signed certificate, queried with curl -skI. Both TLS servers set add_header Strict-Transport-Security "max-age=300" at server level, one with always and one without.

1. A location with its own add_header drops HSTS. /assets/ added only Cache-Control and answered without HSTS, because nginx inherits add_header from the level above only if the current level defines none. If that location is location / or your proxy location, every page loses HSTS while the server block looks right.

2. Without always, error responses go out bare: 200 carried the header, 404 did not. nginx adds headers only to 200, 201, 204, 206, 301, 302, 303, 304, 307 and 308 unless always is set. One good response stores the policy, so this matters less than it looks, but a visitor whose first HTTPS response is an error leaves without it.

3. HSTS needs the redirect. The HTTP server answered 301 with a Location and no HSTS, which is correct: browsers must ignore the header over HTTP (RFC 6797, section 8.1). Without the redirect, an http:// visitor never reaches the response that carries the policy.

curl -skI output from the test, shortened: host name and test ports replaced by example.com, the asset path shortened, and every header line except the status and the ones discussed removed
# add_header ... always; at server level
$ curl -skI https://example.com/
HTTP/1.1 200 OK
Strict-Transport-Security: max-age=300

# location /assets/ has its own add_header Cache-Control
$ curl -skI https://example.com/assets/app.css
HTTP/1.1 200 OK
Cache-Control: public, max-age=86400

# a missing file, still with always
$ curl -skI https://example.com/missing
HTTP/1.1 404 Not Found
Strict-Transport-Security: max-age=300

# second TLS server, add_header without always (/ returned 200 with the header)
$ curl -skI https://example.com/missing
HTTP/1.1 404 Not Found

# plain HTTP server: return 301 https://$host$request_uri;
$ curl -skI http://example.com/
HTTP/1.1 301 Moved Permanently
Location: https://example.com/

05How to enable HSTS in nginx

Send the header from the HTTPS server block only, with always, and repeat it in every location that has its own add_header. nginx 1.29.3 added add_header_inherit merge to append the parent's headers instead; Debian 12's nginx 1.22 lacks it. For several headers, use the include file from the security headers guide, then check a page, an asset and a missing URL with the HTTP headers checker.

nginx: the server-level line, the asset location and the port 80 redirect match the reproduced setup; the repeated line in /assets/ follows the add_header inheritance rule in the nginx docs
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;          # no HSTS here
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;
    # ssl_certificate and ssl_certificate_key as usual

    add_header Strict-Transport-Security "max-age=300" always;

    location /assets/ {
        add_header Strict-Transport-Security "max-age=300" always;   # repeat: this level has its own add_header
        add_header Cache-Control "public, max-age=86400";
    }
}

06How to enable HSTS in Apache

Use mod_headers with Header always set: the always table is applied even to errors and kept across internal redirects such as ErrorDocument handlers, which the default onsuccess table does not guarantee. Set it in the port 443 virtual host only; on port 80, Redirect permanent answers 301 and appends the rest of the path.

Apache 2.4 (from the mod_headers and mod_alias documentation; not reproduced)
# mod_headers must be loaded
<VirtualHost *:443>
    ServerName example.com
    # SSLEngine on, SSLCertificateFile and SSLCertificateKeyFile as usual
    Header always set Strict-Transport-Security "max-age=300"
</VirtualHost>

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent "/" "https://example.com/"
</VirtualHost>

07How to enable HSTS in Caddy

Caddy's automatic HTTPS already redirects HTTP to HTTPS, and its docs do not list HSTS among the defaults: the header directive page shows it as an opt-in example, to use only if you understand the implications. If the backend behind reverse_proxy sends its own value, write >Strict-Transport-Security, which defers the change until the proxy has written its headers.

Caddyfile (from the Caddy header directive documentation; not reproduced)
example.com {
    header Strict-Transport-Security "max-age=300"
    # backend sends its own value? use: header >Strict-Transport-Security "max-age=300"
    reverse_proxy 127.0.0.1:8080          # or your existing handler
}

08How to enable HSTS for WordPress

Set it in the web server or the proxy in front of WordPress, not in PHP. A plugin or header() call only reaches responses WordPress generates; files on disk, such as uploads, CSS and JavaScript, are served without PHP, because WordPress's standard .htaccess hands a request to index.php only when no such file or directory exists. The HTTP-to-HTTPS redirect belongs in the server too.

With your own server block or virtual host, use the configs above. On shared hosting, one .htaccess often serves both HTTP and HTTPS, so make the header conditional on HTTPS (needs AllowOverride FileInfo). If a CDN or proxy forwards requests to the origin over plain HTTP, the condition never matches, so set HSTS at the proxy. Switch the WordPress Address and Site Address to https:// first; a CMS still on http:// is a classic cause of redirect loops.

.htaccess, above the WordPress block (Apache mod_headers with an expression; from the Apache documentation, not reproduced)
Header always set Strict-Transport-Security "max-age=300" "expr=%{HTTPS} == 'on'"

# BEGIN WordPress
# ... WordPress's own rules stay unchanged ...
# END WordPress

09How to enable HSTS on Cloudflare

Behind Cloudflare, browsers get Cloudflare's HTTPS response, so the setting lives there. Cloudflare asks for working HTTPS first and sends the header on HTTPS requests only.

  • On the Edge Certificates page, select Enable HSTS, confirm the warning with I understand, then Next
  • Max Age Header: 1 to 12 months, or 0 to disable; there is no shorter trial value
  • Leave Apply HSTS policy to subdomains and Preload off until the preload checks below pass
  • No-Sniff Header is a separate option that adds X-Content-Type-Options: nosniff
  • Save, then check with curl -sI https://example.com/

10How to enable HSTS with Kubernetes ingress-nginx

ingress-nginx sends HSTS on TLS servers by default: hsts "true", hsts-max-age "31536000", hsts-include-subdomains "true", hsts-preload "false". A new TLS ingress therefore starts at one year with includeSubDomains and skips the trial; lower the values in the controller ConfigMap to follow the rollout below.

The Kubernetes project retired ingress-nginx in March 2026, as announced in November 2025: there are no further releases, bug fixes or security fixes. Existing installations keep working and the Helm charts and images remain available. Check how your next controller handles HSTS before you migrate.

ingress-nginx controller ConfigMap (key names and defaults from the ingress-nginx documentation; use the name and namespace of your installation)
apiVersion: v1
kind: ConfigMap
metadata:
  name: ingress-nginx-controller
  namespace: ingress-nginx
data:
  hsts: "true"
  hsts-max-age: "300"
  hsts-include-subdomains: "false"   # default "true": keep it only if every subdomain serves HTTPS
  hsts-preload: "false"

11How to enable HSTS in Next.js

Next.js sets headers through headers() in next.config. The source "/:path*" matches every path, and headers are checked before the filesystem, so /public files get them too. The security headers example in the Next.js docs sends max-age=63072000; includeSubDomains; preload, which opts you into preload: start short and leave preload out.

headers() needs a running Next.js server and is not supported in a static export (output: "export"); there, set HSTS where the files are served. Behind a proxy or CDN, set it in one place only.

next.config.ts (from the Next.js headers documentation; not reproduced)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async headers() {
    return [
      {
        source: "/:path*",
        headers: [{ key: "Strict-Transport-Security", value: "max-age=300" }],
      },
    ];
  },
};

export default nextConfig;

12What max-age should you use? A safe rollout

Raise max-age in steps and wait out the full max-age of each step before the next, as hstspreload.org recommends: a mistake locks visitors out only for the max-age they already stored. The first steps follow hstspreload.org (5 minutes, 1 week, 1 month) and OWASP (1 day).

Behind GuardX, you switch HSTS on per domain in the dashboard; its max-age options start at 1 day. Preload is a separate opt-in that needs a max-age of at least one year.

Stepmax-ageCheck before you move on
1. Trial300 or 86400 (5 minutes or 1 day)Header on pages, assets, 404s and HTTPS redirects of every covered host; http:// answers 301 to https:// on the same host; no mixed content in the console
2. One week604800No certificate warnings reported; renewal is automated and alerts before expiry
3. One month2592000With includeSubDomains: every name in your DNS zone, including www, staging and internal hosts, has a valid certificate
4. Six months15552000Every certificate has renewed at least once without anyone touching it
5. One year31536000Header still on every response; the minimum for preload
6. Preload, last31536000 or more; includeSubDomains; preloadEvery requirement in the preload section holds, for years

13Should you preload HSTS? Requirements and consequences

Preloading puts the domain on a list built into browsers, so even the first visit uses HTTPS. MDN notes that Google runs the list and all major browsers use it, though it is not part of the standard. hstspreload.org asks projects that give HTTPS advice or offer an HSTS option not to include preload by default.

It is slow to reverse. Removal is possible, but hstspreload.org says it takes months to reach users through Chrome updates, with no guarantees for other browsers, and new entries also take months. It covers every subdomain, internal ones included, so an HTTP-only admin panel, device page or test server stops loading. Sites that stop meeting the requirements may be removed automatically.

hstspreload.org requirementHow to check
A valid certificateEvery hostname, renewed automatically; the SSL/TLS checker shows chain and expiry
Redirect HTTP to HTTPS on the same host, if port 80 is opencurl -sI http://example.com/ points to https://example.com/, not straight to www
All subdomains on HTTPS, including www if it has a DNS recordEvery name in your DNS zone, internal ones included
The header on the base domain over HTTPScurl -sI https://example.com/; an HTTPS redirect, for example to www, must carry it too
max-age of at least 31536000 (one year)Two years (63072000) also passes
includeSubDomains and preload in the headerBoth present; then submit at hstspreload.org

14HSTS, redirect loops and certificate errors

HSTS turns a redirect from HTTPS back to HTTP on the same host into a loop, and keeps it for every visitor who stored the policy. If the origin behind a CDN or proxy redirects HTTPS back to HTTP, the browser upgrades again internally, the server downgrades again, and Chrome stops with ERR_TOO_MANY_REDIRECTS. Fix the redirect at the origin.

Certificate errors become hard stops: RFC 6797 tells browsers to end the connection with no way to proceed, so an expired or mismatched certificate shows Your connection is not private without the click-through link. With includeSubDomains, a subdomain whose port 443 answers in plain HTTP fails the handshake, which Chrome typically reports as ERR_SSL_PROTOCOL_ERROR.

On your own machine, chrome://net-internals/#hsts can query a host and delete its stored policy, though not preloaded entries. That fixes one browser; for visitors, fix the server or send max-age=0 over HTTPS.

Questions

Frequently asked questions

01Do I still need HSTS if I redirect HTTP to HTTPS?
Yes. The redirect happens only after an unencrypted request has left the browser, and anyone on the network can answer it instead of your server. HSTS makes the browser skip that request on every later visit. Keep both: the redirect for first visits, the header for the rest.
02What is a good HSTS max-age?
One year (31536000) or two (63072000) once every hostname is reliably on HTTPS; one year is the minimum for preload. Get there in steps: 5 minutes or a day, a week, a month, six months, then a year.
03How do I remove or disable HSTS?
Send Strict-Transport-Security: max-age=0 over HTTPS; browsers drop the policy when they receive it. It cannot be turned off over HTTP, so keep HTTPS working until the old max-age has run out. A preloaded domain must also request removal at hstspreload.org, which takes months.
04Does HSTS apply to subdomains?
Only with includeSubDomains; otherwise the policy covers just the host that sent it. Browsers store each host's policy separately, so MDN advises every subdomain to send its own header, since a browser may visit a subdomain before the parent domain.
05Why is my HSTS header not working?
Check that it arrives over HTTPS (it is ignored over HTTP), as a real header rather than a meta tag, on a hostname rather than an IP address, and with valid syntax. On nginx, check that a location with its own add_header has not dropped it. If two copies arrive, browsers use the first.

Sources

Sources and verification

nginx behaviour reproduced with nginx 1.22.1 on Debian 12 (loopback test servers, self-signed certificate, curl), November 2026. Apache, Caddy, WordPress, Cloudflare, ingress-nginx and Next.js settings are taken from their official documentation.

  1. 01RFC 6797: HTTP Strict Transport Security (HSTS) · RFC Editor
  2. 02Strict-Transport-Security header · MDN
  3. 03HSTS preload list: submission requirements, deployment recommendations and removal · hstspreload.org
  4. 04HTTP Strict Transport Security Cheat Sheet · OWASP
  5. 05Module ngx_http_headers_module (add_header, always, add_header_inherit) · nginx.org
  6. 06Apache mod_headers: Header directive, always and onsuccess · Apache HTTP Server docs
  7. 07Apache mod_alias: Redirect · Apache HTTP Server docs
  8. 08Expressions in Apache HTTP Server: the HTTPS variable · Apache HTTP Server docs
  9. 09Caddyfile directive: header · Caddy docs
  10. 10Automatic HTTPS · Caddy docs
  11. 11WordPress .htaccess: basic rewrite rules · WordPress Developer Resources
  12. 12HTTP Strict Transport Security (HSTS) · Cloudflare docs
  13. 13ingress-nginx ConfigMap: hsts, hsts-max-age, hsts-include-subdomains, hsts-preload · ingress-nginx docs
  14. 14Ingress NGINX Retirement: What You Need to Know (11 November 2025) · Kubernetes blog
  15. 15kubernetes/ingress-nginx: retirement notice (repository archived 24 March 2026) · GitHub
  16. 16next.config.js: headers · Next.js docs
  17. 17Static exports: unsupported features · Next.js docs
  18. 18Chromium source: HSTS upgrade as an internal 307 redirect (url_request_http_job.cc) · Chromium
  19. 19Chromium source: synthesized redirect headers, "HTTP/1.1 %i Internal Redirect" (redirect_util.cc) · Chromium
  20. 20Chromium source: net-internals HSTS query and delete page · Chromium

Last updated