Security Hardening in NGINX
1. Base Configuration & Global Security Settings
# Global settings
worker_processes auto;
events {
worker_connections 1024;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
client_max_body_size 20M;
# Use a public DNS resolver for upstream lookups
resolver 8.8.8.8 valid=10s;
# Disable NGINX version info in error pages and headers
server_tokens off;
keepalive_timeout 65; # Keeps connections open for reuse up to 65 seconds
sendfile on; # Enable zero-copy file transmission
tcp_nodelay on; # Disable Nagle's algorithm to reduce latency
tcp_nopush on; # Optimize packet transmission (commonly used with sendfile)
gzip on;
gzip_comp_level 5; # Compression level (1-9)
gzip_min_length 256; # Only compress responses larger than 256 bytes
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss;
gzip_vary on;
# Map to generate a nonce for CSP headers based on $request_id
map $request_id $csp_nonce {
"~*" $request_id;
}
# Map to match suspicious or malicious User-Agent strings
# use this carefully as it will block crawlers also
map $http_user_agent $bad_user_agent {
default 0;
~*^$ 1; # Empty User Agent
~*bot 1; # Bots (use caution, some legitimate bots may be blocked)
~*spider 1;
~*crawl 1;
~*[<>]script 1; # Potential XSS attempts
~*(nmap|nikto|wikto|sf|sqlmap|bsqlbf|w3af|acunetix|havij|appscan) 1;
}
# Include additional project configuration
include app.conf;
}2. SSL/TLS Setup & HTTP to HTTPS Redirection
A. Using Let’s Encrypt with Certbot
B. Self-Signed Certificates
3. Security Headers & Content Security Policy (CSP)
4. Mitigating SQL Injection
4. DDoS Protection & Rate Limiting
5. Access Restrictions by IP, GeoIP, and User-Agent
A. IP-based Restrictions
B. User-Agent Filtering
C. Restricting by GeoIP
6. Blocking Sensitive Directories and Files
7. Blocking Bots & Bad Traffic with ModSecurity
8. Proxying to Backend & Handling Subdomains
9. Mitigating OWASP Top 10 Vulnerabilities
10. Final Consolidated Configuration
Last updated