HTTP Strict Transport Security is a mechanism through which web servers declare themselves to be accessible only over secure connections (HTTPS). This mechanism is implemented by configuring the web server to send a HSTS header in its responses. A typical HSTS header looks like the following:
Strict-Transport-Security: max-age=31536000; includeSubDomains
The RFC standard for HTTP Strict Transport Security – RFC6797 specifies under Section 7.2 that a web server should not include this header in plain-text HTTP responses.
From section 7.2:
An HSTS Host MUST NOT include the STS header field in HTTP responses conveyed over non-secure transport.
One way of doing this on Nginx is to place the add_header directive inside an if
block. However add_header
requires the if
to be inside a location
block. This can become cumbersome if you have multiple location blocks in your Nginx config file. I came across the follow elegant solution in an old Nginx TRAC ticket.
map $scheme $hsts_header { https "max-age=31536000; includeSubDomains"; } server { listen 80; listen 443 ssl; add_header Strict-Transport-Security $hsts_header; # Rest of the virtual host configuration # [...] }
Edit your virtual host file and place the map
block above the server
block. Add the add_header
directive inside the server
block. Do a configuration test and reload Nginx if successful.
sudo service nginx configtest sudo service nginx reload
More information about the Nginx map
directive can be found here – http://nginx.org/en/docs/http/ngx_http_map_module.html#map.
Leave a Reply