NGINX

Enforce HTTPS with HTTP Strict Transport Security (HSTS)

Prevent downgrade attacks and ensure all communication happens over HTTPS by enforcing HTTP Strict Transport Security (HSTS) on your web server.

# Nginx Configuration Example
server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$host$request_uri; # Redirect HTTP to HTTPS
}

server {
    listen 443 ssl;
    server_name yourdomain.com;

    # SSL configuration (omitted for brevity, assume valid certs are configured)
    # ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    # ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    # include /etc/letsencrypt/options-ssl-nginx.conf;
    # ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # Implement HSTS header: max-age is 1 year (31536000 seconds)
    # includeSubDomains: applies HSTS to all subdomains
    # preload: Allows preloading this HSTS configuration into browsers (requires submission to hstspreload.org)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    location / {
        # Your application's proxy pass or root directory
        proxy_pass http://localhost:3000; # Example for a Node.js app
        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: HTTP Strict Transport Security (HSTS) is a security policy mechanism that helps protect websites against man-in-the-middle attacks, especially SSL stripping attacks. By setting the `Strict-Transport-Security` header, you instruct browsers to only interact with your domain using HTTPS for a specified duration (`max-age`). The `includeSubDomains` directive extends this policy to all subdomains, while `preload` allows inclusion in browser HSTS preload lists for enhanced protection from the very first visit. This ensures secure communication and prevents users from accidentally accessing your site over insecure HTTP.

Need help integrating this into your project?

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

Hire DigitalCodeLabs