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.
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
}
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;
}
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';";
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;
Control how much referrer information is shared when users navigate away from your site by adding this header:
add_header Referrer-Policy "no-referrer";
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=()";
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.