BASH

Enforce HTTPS with HSTS (HTTP Strict Transport Security) in Nginx

Configure Nginx to enforce HTTP Strict Transport Security (HSTS), forcing browsers to communicate with your website exclusively over secure HTTPS connections.

# Nginx configuration for HSTS
# This block typically goes inside your server block for HTTPS traffic

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name example.com www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

    # Add the HSTS header
    # max-age specifies the time in seconds (e.g., 1 year = 31536000)
    # includeSubDomains: Apply HSTS to all subdomains
    # preload: Allows browsers to hardcode HSTS for your domain (requires submission)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # Optional: Redirect HTTP to HTTPS
    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    }

    # ... other Nginx configurations (root, index, location blocks, etc.)
}

# You might also have a separate HTTP server block to redirect all traffic to HTTPS:
# server {
#     listen 80;
#     listen [::]:80;
#     server_name example.com www.example.com;
#     return 301 https://$host$request_uri;
# }
How it works: This Nginx configuration snippet demonstrates how to implement HTTP Strict Transport Security (HSTS). The `add_header Strict-Transport-Security` directive instructs browsers to communicate with the server exclusively over HTTPS for a specified duration (`max-age`). `includeSubDomains` extends this policy to all subdomains, and `preload` allows the domain to be included in browsers' HSTS preload lists for maximum security. This header helps prevent man-in-the-middle attacks by ensuring browsers never connect over insecure HTTP, even if a user explicitly tries to.

Need help integrating this into your project?

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

Hire DigitalCodeLabs