How To Implement Security Headers In Nginx

How to Implement Security Headers in Nginx

Securing your Nginx web server is crucial for protecting your website and users. One effective way to enhance security is by implementing proper security headers. This guide will walk you through the process step by step.

Step 1: Open Nginx Configuration

Connect to your server and open your Nginx configuration file. This is typically located at /etc/nginx/nginx.conf or /etc/nginx/sited-enabled/yoursite.com (Debian and Ubuntu), or /etc/nginx/conf.d/nginx.conf (RHEL and CentOS).

sudo nano /etc/nginx/nginx.conf

Or:

sudo nano /etc/nginx/sited-enabled/yoursite.com

Or:

/etc/nginx/conf.d/nginx.conf

Step 2: Add Security Headers

Insert the following lines at the appropriate location in your Nginx configuration file to add security headers:

  1. Add headers to the config file:
    • server {
      ....


      add_header X-XSS-Protection "1; mode=block" always;
      add_header X-Content-Type-Options "nosniff" always;
      add_header Referrer-Policy "strict-origin-when-cross-origin" always;
      add_header Content-Security-Policy "default-src 'self'" always;
      add_header Permissions-Policy "interest-cohort=()" always;
      add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
      add_header X-Frame-Options "SAMEORIGIN" always;
      add_header Referrer-Policy "no-referrer-when-downgrade" always;

      ....
      }
  2. For more information regarding Content-Security-Policy, Please view our guide on How to implement Content-Security-Policy Security Headers in Nginx

Step 4: Save and Restart Nginx

Save your changes and restart Nginx to apply the new configuration:

sudo systemctl restart nginx

Step 5: Verify Configuration

Ensure that the security headers are applied correctly by visiting your website and checking the response headers using browser developer tools or online security header checking tools.