Add Security Headers to .htaccess

474
some featured image

Make your website more secure and trustworthy by adding these security headers to your .htaccess file:

<IfModule mod_headers.c>
Header always set Strict-Transport-Security: "max-age=31536000" env=HTTPS
Header always set Content-Security-Policy "upgrade-insecure-requests"
Header always set X-Content-Type-Options "nosniff"
Header always set X-XSS-Protection "1; mode=block"
Header always set Expect-CT "max-age=7776000, enforce"
Header always set Referrer-Policy: "no-referrer-when-downgrade"
Header set X-Permitted-Cross-Domain-Policies "none"
Header set X-Frame-Options "sameorigin"
</IfModule>

Details:

You should be careful about where you insert the code in your WordPress site’s .htaccess file. The order and placement of directives in .htaccess can impact how they are processed.

Here are some guidelines:

Insertion Point:

  • If your WordPress site already has an .htaccess file, find an appropriate insertion point where you can add the new directives without disrupting existing rules.

WordPress Rules:

  • Ideally, place the new directives after the standard WordPress rules that are usually added by WordPress itself. This ensures that your custom rules do not interfere with the core functionality of WordPress.

Plugin Rules:

  • Some plugins may also add their own rules to the .htaccess file. If possible, place your custom rules after any rules added by plugins to avoid conflicts.

Backup Before Editing:

  • Before making any changes, create a backup of your current .htaccess file. This allows you to revert to the original state if anything goes wrong.

Testing:

  • After adding the new directives, thoroughly test your website to ensure that everything works as expected. Pay attention to security-related headers to make sure they are being applied.

Here’s an example of what your .htaccess file might look like:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

# Custom Security Headers
<IfModule mod_headers.c>
    Header always set Strict-Transport-Security "max-age=31536000" env=HTTPS
    Header always set Content-Security-Policy "upgrade-insecure-requests"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Expect-CT "max-age=7776000, enforce"
    Header always set Referrer-Policy "no-referrer-when-downgrade"
    Header set X-Permitted-Cross-Domain-Policies "none"
    Header set X-Frame-Options "sameorigin"
</IfModule>

In this example, the custom security headers are added after the standard WordPress rules. Always remember to check the website after making changes to ensure everything is functioning correctly.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

CAPTCHA