APACHE

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

Implement HTTP Strict Transport Security (HSTS) in Apache to force browsers to always use HTTPS, protecting your users from protocol downgrade attacks and cookie hijacking.

# In your Apache Virtual Host configuration for HTTPS (e.g., /etc/apache2/sites-available/your_site-ssl.conf)

<VirtualHost *:443>
    ServerName yourdomain.com
    # ... other SSL/TLS configurations ...

    # Enable Strict Transport Security (HSTS)
    # This header should ONLY be added on the HTTPS VirtualHost.
    # max-age: The time in seconds that the browser should remember that this site is only to be accessed using HTTPS.
    # includeSubDomains: Apply this rule to all subdomains as well.
    # preload: Opt-in to the HSTS preload list (requires certain conditions and submitting your domain).
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

    # Optional: Redirect HTTP to HTTPS permanently (highly recommended)
    # This ensures all initial requests are upgraded
    # For this, you would typically have a separate HTTP VirtualHost or rewrite rules.
    # Example HTTP redirect (ensure this is in your non-SSL VirtualHost or global config):
    # <VirtualHost *:80>
    #     ServerName yourdomain.com
    #     Redirect permanent / https://yourdomain.com/
    # </VirtualHost>

    # ... other Apache configurations (DocumentRoot, ErrorLog, etc.) ...
</VirtualHost>
How it works: This Apache configuration snippet demonstrates how to implement HTTP Strict Transport Security (HSTS). HSTS is an HTTP header that tells browsers to always connect to your website using HTTPS, even if the user explicitly types `http://`. This protects against protocol downgrade attacks and cookie hijacking. The `max-age` directive specifies how long the browser should remember this policy, `includeSubDomains` extends it to subdomains, and `preload` allows inclusion in browser HSTS preload lists for enhanced security. This header should only be set on the HTTPS virtual host for proper functionality.

Need help integrating this into your project?

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

Hire DigitalCodeLabs