BASH
Configure HTTP Strict Transport Security (HSTS) in Nginx
Enhance web security by configuring HSTS in Nginx, forcing browsers to communicate with your server exclusively over HTTPS and preventing downgrade attacks.
# Nginx configuration for HSTS
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
# SSL certificate and key paths
ssl_certificate /etc/nginx/ssl/yourdomain.com.crt;
ssl_certificate_key /etc/nginx/ssl/yourdomain.com.key;
# HSTS header
# max-age is in seconds (e.g., 31536000 seconds = 1 year)
# includeSubDomains is optional, but recommended if all subdomains use HTTPS
# preload is optional, but allows browsers to hardcode HSTS for your domain
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# Other server configurations...
root /var/www/yourdomain.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
# Optional: Redirect HTTP to HTTPS
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
How it works: This Nginx configuration snippet shows how to implement HTTP Strict Transport Security (HSTS). HSTS is a security policy mechanism that helps protect websites against man-in-the-middle attacks and cookie hijacking by forcing web browsers to interact with the server only over secure HTTPS connections. The `Strict-Transport-Security` header tells the browser to automatically convert all future HTTP requests for the specified domain into HTTPS requests for a given `max-age` period. `includeSubDomains` extends this policy to all subdomains, and `preload` allows the domain to be submitted to a browser's preloaded HSTS list for maximum protection.