NGINX
Enforcing HTTPS and HTTP Strict Transport Security (HSTS) with Nginx
Configure Nginx to automatically redirect HTTP traffic to HTTPS and enable HSTS, significantly improving your website's transport layer security.
# Nginx configuration for enforcing HTTPS and HSTS
# HTTP server block: Redirects all HTTP traffic to HTTPS
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com; # Replace with your domain
# Permanent redirect to HTTPS
return 301 https://$host$request_uri;
}
# HTTPS server block
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.example.com; # Replace with your domain
# SSL certificate paths (replace with your actual paths)
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Recommended SSL/TLS settings for security
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
ssl_stapling on; # Requires valid OCSP responder
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s; # Google DNS or your preferred DNS resolver
resolver_timeout 5s;
# HSTS Header: Tells browsers to only connect via HTTPS for a specified duration
# 'max-age' is in seconds (e.g., 1 year = 31536000).
# 'includeSubDomains' applies the policy to all subdomains.
# 'preload' allows inclusion in browsers' HSTS preload lists (requires submission).
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# Other security headers (optional but recommended)
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always; # Or more restrictive
root /var/www/html; # Your web root
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# Optional: Proxy pass to a backend application
# location /api/ {
# proxy_pass http://localhost:3000;
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-Proto $scheme;
# }
}
How it works: This Nginx configuration snippet demonstrates how to enforce HTTPS for all incoming traffic and enable HTTP Strict Transport Security (HSTS). The HTTP server block redirects any insecure HTTP request to its HTTPS equivalent, ensuring encrypted communication. The HTTPS server block then applies the HSTS header, which instructs browsers to only interact with the site over HTTPS for a specified period, even if a user explicitly types "http://". This helps prevent various man-in-the-middle attacks and cookie hijacking.