How to enable HSTS on your server

How to enable HSTS on Apache, NGINX and Lighttpd

First we will understand What is HSTS Technology?

HSTS (HTTP Strict Transport Security) is an advanced security mechanism which was developed by IEFT and intended to secure the website and users against the cookie hijacking and protocol downgrade attacks. The main function of the HSTS policy is the web browser will only communicate with the server using secured HTTPS connection but not with the HTTP connection.

As per the HSTS policy, the browser should only access the server with the secured channel.

Let’s see the practical examples of HSTS Policy

A user enters HTTP version of a domain if HSTS is enabled the browser will load the HTTPS version of the website.

Check the image for more information.

 

How to enable HSTS in Apache2

To enable the HSTS in Apache2, you need to update the configuration file by adding the following line of code in VirtualHost section.

You can find the Apache configuration file here, (/etc/apache2/sites-enabled/website.conf)

# Optionally load the headers module:

LoadModule headers_module modules/mod_headers.so

<VirtualHost 67.89.123.45:443>

Header always set Strict-Transport-Security “max-age=63072000; includeSubdomains;”

</VirtualHost>

As per the above line of code, when a user visits your website, the above header will load first and the expiration time is 2 years (63072000 in seconds).

Now to redirect your http website visitors into https version add following line of code in Virtual Host.

<VirtualHost *:80>

[…]

ServerName example.com

Redirect permanent / https://example.com/

</VirtualHost>

Modrewrite is also another option to divers users into https version, here is the line of code you need to add in your VirtualHost section.

<VirtualHost *:80>

[…]

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

</IfModule>

</VirtualHost>

Save the config file and restart your Apache server, the HSTS will be active.

How to enable HSTS in NGINX

To enable the HSTS in NGINX, update the following line of code in config file’s server Block.

add_header Strict-Transport-Security “max-age=63072000; includeSubdomains; “;

Restart the NGINX server.

How to enable HSTS in Lighttpd

To enable HSTS in Lighttpd, update the following line of code in the configuration (.conf) file.

server.modules += ( “mod_setenv” )

$HTTP[“scheme”] == “https” {

setenv.add-response-header = ( “Strict-Transport-Security” => “max-age=63072000; includeSubdomains; “)

}

Restart the Lighttpd server.

END