NGINX

Enforcing HTTPS with HTTP Strict Transport Security (HSTS)

Implement HSTS in your Nginx configuration to force browsers to connect only via HTTPS, enhancing security against man-in-the-middle attacks.

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

server {
    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;

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

    # ... other Nginx configurations
}
How it works: HTTP Strict Transport Security (HSTS) is a web security policy mechanism that helps protect websites against man-in-the-middle attacks and cookie hijacking. When a server sends the `Strict-Transport-Security` header, it instructs the browser to only connect to the site using HTTPS for a specified duration (`max-age`). The `includeSubDomains` directive applies this policy to all subdomains, and `preload` indicates consent for inclusion in browsers' HSTS preload lists.

Need help integrating this into your project?

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

Hire DigitalCodeLabs