NGINX

Implement HTTP Strict Transport Security (HSTS)

Configure Nginx to enforce HTTPS connections using HTTP Strict Transport Security (HSTS), protecting against man-in-the-middle attacks and ensuring secure browser communication.

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    # SSL Configuration (assuming these are already set up)
    # ssl_certificate /etc/nginx/ssl/example.com.crt;
    # ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # HSTS Configuration: instructs browsers to only use HTTPS for 1 year (31536000 seconds)
    # includeSubDomains: applies HSTS to all subdomains
    # preload: opt-in to browser's HSTS preload list (requires additional submission)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # ... other server configurations ...
}
How it works: This Nginx configuration snippet demonstrates how to implement HTTP Strict Transport Security (HSTS). The first server block redirects all HTTP traffic to HTTPS. The second server block, configured for HTTPS, adds the 'Strict-Transport-Security' header. This header tells supporting browsers to only interact with the domain over HTTPS for the specified 'max-age' duration, even if a user explicitly types 'http://' or clicks an HTTP link. 'includeSubDomains' extends this policy to subdomains, and 'preload' allows inclusion in browser HSTS preload lists for immediate enforcement.

Need help integrating this into your project?

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

Hire DigitalCodeLabs