NGINX

Enforce HTTPS with HSTS on Nginx

Configure Nginx to implement HTTP Strict Transport Security (HSTS), forcing browsers to use HTTPS and preventing man-in-the-middle attacks.

# Redirect HTTP to HTTPS (standard practice before HSTS)
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

# HTTPS server block with HSTS
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com www.example.com;

    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # HSTS Configuration
    # 'max-age' defines how long (in seconds) the browser should remember to only access the site via HTTPS.
    # 'includeSubDomains' applies the policy to all subdomains.
    # 'preload' indicates consent to be included in the HSTS preload list for browsers (requires specific submission).
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # Other SSL/TLS best practices (optional but recommended)
    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:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256';
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1h;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    root /var/www/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
}
How it works: This Nginx configuration snippet demonstrates how to enforce HTTPS using HTTP Strict Transport Security (HSTS). The `add_header Strict-Transport-Security` directive tells browsers that the site should only be accessed over HTTPS for a specified duration (`max-age`). The `includeSubDomains` and `preload` directives extend this policy. This forces browsers to automatically upgrade HTTP requests to HTTPS, even if the user explicitly types HTTP, significantly reducing the risk of man-in-the-middle attacks and cookie hijacking.

Need help integrating this into your project?

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

Hire DigitalCodeLabs