enable http strict transport policy in nginx

How to Enable HTTP Strict Transport Policy (HSTS) in NGINX

HTTP Strict Transport Policy (HSTS) protects your website from man-in-the-middle attacks, protocol downgrade attacks and coookie hijacking. By default, HSTS is not enabled in NGINX server. In this article, we will look at how to enable HTTP Strict Transport Policy (HSTS) in NGINX.

How to Enable HTTP Strict Transport Policy in NGINX

Here are the steps to enable HSTS in NGINX.

1. Open NGINX configuration

Open terminal and run the following command to open NGINX configuration file.

$ sudo vi /etc/nginx/nginx.conf

Depending on your installation, NGINX configuration file may be alternatively located at /usr/local/nginx/conf or /usr/local/etc/nginx.

Also read : Redirect to Another Domain without changing URL

2. Enable HTTP Strict Transport Policy

We will use the add_header directive to set the Strict-Transpost-Security header for our NGINX server. Here is an example,

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

In the above line, we specify the set the Strict-Transport-Security header for 365 days. We also tell NGINX to preload the domain and subdomains to improve performance. With this setting, browser will automatically request the HTTPS version of your web pages instead of the HTTP ones.

You need to add this in server block of your NGINX configuration file, that listens to port 443 (SSL/HTTPS).

server {
   listen 443
   add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";

If you ever want to disable HSTS on your website, just comment or remove the above line in NGINX configuration file.

Also read : How to Check What User NGINX is Running As

3. Restart NGINX server

Restart NGINX server to apply changes.

$ sudo service nginx restart

There are many online tools like Qualsys SSL labs that allows you to check if HSTS is enabled on your NGINX server. Use them to verify HTTP Strict Transport Policy for your website.

In this article, we have learnt how to enable HTTP Strict Transport Policy (HSTS) for NGINX server. HSTS tells browsers to always use HTTPS instead of using HTTP, thereby avoiding the need for redirect from HTTP to HTTPS. Nevertheless, you must still redirect HTTP requests to HTTPS. HSTS also improves website performance slightly by reducing its server load.

Also read : How to List NGINX Modules & Compiled Flags

Leave a Reply

Your email address will not be published. Required fields are marked *