How to Implement HSTS in Apache?

Implementing HTTP Strict Transport Security (HSTS) in Apache is a crucial step toward securing your website by forcing browsers to connect only via HTTPS. This article provides a straightforward guide on how to enable HSTS, including enabling the necessary Apache modules, editing your configuration files, and verifying that the security header is working correctly. By enforcing HSTS, you protect your users from man-in-the-middle attacks, SSL stripping, and cookie hijacking.

Step 1: Enable the Apache Headers Module

Before you can add the HSTS header, you must ensure that Apache’s mod_headers module is enabled. This module allows you to merge, replace, or remove HTTP response headers.

On Debian-based systems (like Ubuntu), run the following command in your terminal: sudo a2enmod headers

On Red Hat-based systems (like CentOS or RHEL), this module is typically enabled by default. You can verify it by restarting your Apache service: sudo systemctl restart apache2 or sudo systemctl restart httpd

Step 2: Configure the HSTS Header

To implement HSTS, you need to add the Strict-Transport-Security header to your Apache configuration. It is highly recommended to add this rule only within your HTTPS virtual host configuration file (usually running on port 443), rather than the global configuration or the HTTP file.

Open your SSL virtual host configuration file (e.g., /etc/apache2/sites-available/default-ssl.conf) and insert the following line inside the <VirtualHost *:443> block:

Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"

Here is a breakdown of the directives used in this header:

Step 3: Test and Restart Apache

Before applying the changes to your live environment, test your Apache configuration syntax to ensure there are no errors.

Run the configuration test command: sudo apachectl configtest

If the output returns Syntax OK, restart the Apache service to apply the new security policy: sudo systemctl restart apache2

Step 4: Verify the HSTS Implementation

After restarting Apache, you should verify that the HSTS header is being sent correctly by using a command-line tool like curl.

Run the following command, replacing your domain name accordingly: curl -I https://yourdomain.com

Look for the following line in the terminal output: Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

If you see this header in the response, your Apache server is successfully implementing HTTP Strict Transport Security.