Hardening Nginx for Static Websites

This guide explains how to harden your Nginx configuration for a static website, ensuring your server is protected against common threats. The steps include adding essential security headers, blocking unnecessary access, and configuring SSL/TLS securely.

Step-by-Step Guide

  1. Step 1: Disable Directory Listings

    Directory listings can expose the structure of your website to unwanted visitors. To prevent this, disable directory listings in the Nginx configuration by adding this inside your location / block:

    location / {
        try_files $uri $uri/ =404;
        autoindex off; # Disable directory listing
    }
  2. Step 2: Block Access to Hidden Files

    Files like .git or .env should not be publicly accessible. Block access to these hidden files by adding this to your Nginx configuration:

    location ~ /\.(?!well-known).* {
        deny all;
    }
  3. Step 3: Add Security Headers

    Add the following headers to protect against various attacks such as cross-site scripting (XSS), content-type sniffing, and clickjacking:

    add_header X-Frame-Options "DENY";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";
    add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self';";
  4. Step 4: Enable HSTS (HTTP Strict Transport Security)

    HSTS ensures browsers always use HTTPS to connect to your site. Add this to your HTTPS server block:

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
  5. Step 5: Set a Referrer Policy

    Control how much referrer information is shared when users navigate away from your site by adding this header:

    add_header Referrer-Policy "no-referrer";
  6. Step 6: Control Browser Permissions

    Use the Permissions Policy header to control what browser features (e.g., geolocation, microphone) can be used on your site:

    add_header Permissions-Policy "geolocation=(), microphone=(), camera=()";

Testing Your Configuration

After updating your Nginx configuration with these hardening steps, it’s important to test your setup. There are various online tools available to analyze your website’s security headers and SSL/TLS configuration. These tools will help ensure that your changes have been applied correctly and identify any remaining vulnerabilities.