How to enable HSTS in Nginx

Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.
Subscribe
"The best Linux newsletter on the web"

Hello, friends. In this post, you will learn how to enable HSTS in Nginx. This is simple and useful in configurations made to increase security.

Introduction – What is HSTP?

HSTS is short for HTTP Strict Transport Security, which in its best translation means HTTP Strict Transport Security. It functions as a security policy that helps to improve the security of the connection to the server and avoid vulnerabilities.

HSTS wants to put an end to potential vulnerabilities by instructing the browser that a domain can only be accessed using HTTPS. This way, it will be forced to use SSL whenever it establishes a connection to your website.

So, it is a good practice to enable it on your server.

How to enable HSTS in Nginx

Assuming that Nginx is installed and configured correctly for your needs.

As you know, the global configuration of Nginx resides in the file /etc/nginx/nginx.conf but also each Virtualhost (ServerBlocks) has its file, and it is convenient that it is from there that you make the configuration.

In summary, you have to add the following directive

add_header Strict-Transport-Security "max-age=31536000;

Of course, you have to do this inside the server section.

So, a sample configuration could look like this:

server {
access_log off;
error_log logs/error_log warn;
        listen xx.xx.xx.xx.xx:443 ssl spdy;
        server_name unixcop.com
        add_header Strict-Transport-Security "max-age=31536000";

In this configuration, max-age is set to be a unit expressed in seconds. The value shown is for one year.

Optionally, but recommended, you can make this behavior inherited to all subdomains.

To do so, then add includeSubDomains; like this

server {
access_log off;
error_log logs/error_log warn;
        listen xx.xx.xx.xx.xx:443 ssl spdy;
        server_name unixcop.com
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; always";

The always parameter ensures that the header is set for all responses, including internally generated error responses. This is according to a post on the Nginx blog.

To apply the changes, then restart Nginx

sudo systemctl reload nginx

Now yes, HSTS is ready and enabled!!!!

Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.
Subscribe
"The best Linux newsletter on the web"
Angelo
Angelo
I am Angelo. A systems engineer passionate about Linux and all open-source software. Although here I'm just another member of the family.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest articles

Join us on Facebook