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:
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload" always;
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