APACHE

Prevent Clickjacking with Apache X-Frame-Options

Learn to configure the Apache web server to use the X-Frame-Options header, preventing clickjacking attacks by controlling whether your site can be embedded in an iframe.

# This configuration goes into your Apache virtual host file
# (e.g., /etc/apache2/sites-available/your-site.conf)
# or in an .htaccess file (if AllowOverride All is enabled for your directory).

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html

    # Redirect HTTP to HTTPS (recommended as part of overall security)
    # RewriteEngine On
    # RewriteCond %{HTTPS} off
    # RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/html

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/example_com.crt
    SSLCertificateKeyFile /etc/ssl/private/example_com.key

    # X-Frame-Options to prevent Clickjacking
    # DENY: The page cannot be displayed in a frame, regardless of the site attempting to do so.
    # SAMEORIGIN: The page can only be displayed in a frame on the same origin as the page itself.
    # ALLOW-FROM uri: The page can only be displayed in a frame on the specified origin.
    #                  Note: ALLOW-FROM has limited browser support and is discouraged.
    #                  Consider Content-Security-Policy frame-ancestors directive instead for modern browsers.
    Header always set X-Frame-Options "SAMEORIGIN"
    # Or to completely deny: Header always set X-Frame-Options "DENY"

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride None # If using .htaccess, change this to AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
How it works: This Apache configuration snippet demonstrates how to mitigate clickjacking attacks using the `X-Frame-Options` HTTP header. By setting `Header always set X-Frame-Options "SAMEORIGIN"`, the server instructs browsers to only allow the page to be rendered within an `<frame>`, `<iframe>`, `<embed>`, or `<object>` if the framing page originates from the same domain. Using `"DENY"` would prevent framing entirely from any origin. This helps protect users from unwittingly clicking on malicious elements overlaid on your site.

Need help integrating this into your project?

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

Hire DigitalCodeLabs