How to configure HSTS in Nginx

HSTS (HTTP Strict Transport Security) is a response header that tells the browser that the site should only be opened via HTTPS.

Configurable by adding one line to the server block for your site:

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

But before adding it, you must set up redirection from http port 80 to https for the main domain, as well as for all subdomains, for example:

server {
    listen 80;
    listen [::]:80;
    server_name ixnfo.com www.ixnfo.com;
    
    return 301 https://$host$request_uri; 
}

It’s worth noting that enabling HSTS will make it impossible to open the main domain or any subdomains via HTTP, as the domain will be added to the browser’s database. Disabling/removing it may take months, until, for example, a new version of Google Chrome or Firefox is released.

Let’s check the configuration and restart nginx to apply the changes:

nginx -t
service nginx restart

After adding it, check it on hstspreload.org. If everything is OK, a button will appear that says “Submit ixnfo.com to the HSTS preload list.” After a while, check again; it should say, for example, “ixnfo.com is currently preloaded.”

max-age=31536000 is the time in seconds the browser should remember that the site is only accessible via HTTPS.
31536000 seconds = 1 year, which is the minimum recommended value for preload.

includeSubDomains – required parameter, applies the HSTS policy to all subdomains.

preload is a recommended setting. It means you agree to add the domain to the HSTS preload list, which is hardcoded in browsers. Without it, the domain will not be added to the list. Once added, you must submit a request to hstspreload.org.

always – it is recommended that the HSTS header be sent even on errors, although its effect only occurs on successful responses (200).

List of HSTS preloads in Firefox: searchfox.org/mozilla-central/source/security/manager/ssl/nsSTSPreloadList.inc

See also my article:
Installing Certbot in Ubuntu

Leave a comment

Leave a Reply