Adding HSTS to nginx config

Solution 1:

HSTS tells the browser to always use https, rather than http. Adding that configuration may reduce the need for forwarding from http to https, so it may very slightly increase website performance and very slightly decrease server load.

For reference, here's the security headers I use on my Nginx based websites. I save this to a single file and include it from all servers that need it, including http and https servers. It allows some common resources like Google and Facebook to load.

# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header Content-Security-Policy "default-src 'self';";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "origin";


You still need the http to https redirection in place.

Solution 2:

The accepted answer is great but has become outdated and has a flaw that I have found while researching it line-by-line.

The duration of the HSTS header must be at least three months to satisfy security requirements. I used the following in my security headers snippet to get an A+ on the SSL test:

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

Secondly, use of X-Frame-Options is deprecated (and was never supported by many/most major browsers). The current standard (ie implemented in all major modern browsers) is is Content-Security-Policy (CSP).

add_header Content-Security-Policy 'frame-ancestors https://mywebapp.mywebsite.example';

As is evident from the example CSP headers will have to be set on a per-site basis (barring clever regex/etc that I haven't seen yet).