What Is HSTS and How Do You Enable It? (HTTP Strict Transport Security)

HSTS (HTTP Strict Transport Security) is a security header that tells the browser "connect to me over HTTPS only". Used together with a 301 redirect, it prevents even the first http:// request to your site from being intercepted (SSL stripping).

Why is HSTS needed?

If you use only a 301 redirect, the visitor's browser first reaches the site over http:// and is then redirected to HTTPS. That short first request is an open window for an attacker on the network. With HSTS enabled, the browser converts the request directly to HTTPS without ever sending it, even if http is typed in the address bar.

Anatomy of the header

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  • max-age — how many seconds the browser remembers this rule (31536000 = 1 year).
  • includeSubDomains — applies the rule to all subdomains too.
  • preload — a request to add your site to the browsers' built-in "HTTPS only" list (see the caution below).

Enabling it in Nginx

Add it to your HTTPS server block:

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Enabling it in Apache

With mod_headers enabled, add it to the virtual host or .htaccess:

Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"

Things to watch out for

  • Make sure HTTPS works fully first. While HSTS is active, HTTP access to the site is completely blocked on the browser side; if your certificate is broken, visitors cannot reach the site.
  • Start with a low max-age. On the first try use max-age=300 (5 minutes), and once everything works raise it to 1 year.
  • Don't rush preload. Getting on the preload list is permanent and removal takes weeks; don't add it until you're sure all your subdomains will stay on HTTPS permanently.

Summary

HSTS makes your HTTPS mandatory with a single-line header and closes the first-request gap. Make sure your certificate works flawlessly first; if you don't have one, create it with our free SSL wizard, then enable HSTS with a low max-age.