← Back to all snippets
BASH

Enforce HTTPS with HSTS in Nginx

Configure Nginx to implement HTTP Strict Transport Security (HSTS) to force clients to use HTTPS, protecting against downgrade attacks and cookie hijacking.

server {
    listen 443 ssl http2;
    server_name your_domain.com www.your_domain.com;

    ssl_certificate /etc/nginx/ssl/your_domain.com.crt;
    ssl_certificate_key /etc/nginx/ssl/your_domain.com.key;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256';
    ssl_prefer_server_ciphers off;

}

server {
    listen 80;
    server_name your_domain.com www.your_domain.com;
    return 301 https://$host$request_uri;
}
How it works: This Nginx configuration snippet demonstrates how to implement HTTP Strict Transport Security (HSTS). Placed within the HTTPS server block, the `add_header Strict-Transport-Security` directive instructs browsers to *only* access your domain over HTTPS for a specified `max-age` period (here, 1 year). This helps prevent downgrade attacks (where attackers force connections to insecure HTTP) and protects against cookie hijacking, significantly enhancing user security. The `includeSubDomains` and `preload` directives further extend this protection to subdomains and enable inclusion in browser-level HSTS lists, respectively. A corresponding HTTP server block is also shown to redirect all initial HTTP requests to HTTPS.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs