How to Enable HSTS (HTTP Strict Transport Security) Policy in Nginx & Apache

According to Netcraft’s study, 95% of HTTPS servers are vulnerable to Man-in-the-Middle attacks. Therefore, it is very important to implement HSTS properly. HSTS (HTTP Strict Transport Security) is a policy that protects websites against malicious attacks such as clickjacking, protocol downgrades, and man-in-the-middle attacks as explained in my earlier article. In this article, we shall see various steps to Enable HSTS on NGINX and Apache.

How to Enable HSTS on Nginx

Open your Nginx configuration file for the domain you need to enable HSTS.

For eg: /etc/nginx/conf.d/tg.conf

Add the below line to your server block of HTTPS:

DO NOT ADD HSTS to HTTP block
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload" always;
includeSubDomains parameter

The optional includeSubDomains parameter tells the browser that the HSTS policy also applies to all subdomains of the current domain.

Always parameter

The always parameter ensures that the header is set for all responses, including internally generated error responses.

To have the HSTS configured for a timespan of 1 year set max-age to 31536000 (in secs). It must be at least 3 months to satisfy security requirements.

Restart Nginx service

Before restarting, verify the configuration file as below:

# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Restart the Nginx server to take the new changes.

# systemctl restart nginx

How to Enable HSTS on Apache

To enable HSTS on Apache, we need to have the mod_headers module installed. Run the below command to find if the module is installed already.

# apachectl -M | grep headers
 headers_module (shared)

if you have it, then let’s proceed to configure the header settings of the domain you need to enable HSTS. Open the configuration file that contains the VirtualHost that uses SSL.

For eg: /etc/httpd/conf.d/tg.conf

Add the below configuration inside your VirtualHost for port 443 as below:

<VirtualHost *:443>
......
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
......
</VirtualHost>

Restart Apache service

Before restarting, verify the configuration file as below:

# apachectl configtest
Syntax OK

If the syntax is OK, restart the Apache server to take the new changes.

# systemctl restart httpd       ## Redhat systems

# systemctl restart apache2     ## Debian systems

That’s it! Test the webserver to see if the HSTS has been enabled.

$ curl -kIs https://example.com | grep Strict
Strict-Transport-Security: max-age=31536000; includeSubDomains
Updated on November 29, 2021

Was this article helpful?

Related Articles

Leave a Comment