Additional Security Headers


There are always people that are interested in running things as secure as possible. You should need to place this code into a file within the mu-plugins directory to ensure it gets fired as early as possible when loading the front end of the website. I have been able to get at least an A if not an A+ rating on using the following must use plugin.


Plugin Name: Additional Security Headers
Plugin URI:
Description: This adds additional security headers to the front end of the website that can help protect people browsing.
Author: billiardgreg
Author URI:
License: GPL2

function wpcms_additionalsecurityheaders( $headers ) {
  if ( !is_admin() ) {
    $headers['Referrer-Policy']             = 'no-referrer-when-downgrade'; 
    $headers['X-Content-Type-Options']      = 'nosniff';
    $headers['X-XSS-Protection']            = '1; mode=block;';
    $headers['Permissions-Policy']          = 'geolocation=(self "'.site_url().'"); microphone=(); camera=();';
    $headers['Content-Security-Policy']     = 'upgrade-insecure-requests;'; 
    $headers['Strict-Transport-Security']   = 'max-age=31536000; includeSubDomains;';
    $headers['X-Frame-Options']             = 'SAMEORIGIN';

  return $headers;
add_filter( 'wp_headers', 'wpcms_additionalsecurityheaders' );

If you want a more restrictive security header, you can modify the content-security-policy to only specify what foreign script or items you want to include instead of allowing it with the above policy.

$headers['Content-Security-Policy'] = "default-src 'self';";
$headers['Content-Security-Policy'] .= "font-src 'self' data:;";
$headers['Content-Security-Policy'] .= "style-src 'self' 'unsafe-inline';";
$headers['Content-Security-Policy'] .= "frame-src 'self'; ";
$headers['Content-Security-Policy'] .= "script-src 'self' 'unsafe-inline'; ";
$headers['Content-Security-Policy'] .= "script-src-elem 'self' 'unsafe-inline'; ";
$headers['Content-Security-Policy'] .= "connect-src 'self';";
$headers['Content-Security-Policy'] .= "img-src 'self' data:;";

This will allow you to include some important items like WP cached images, gravatars, google analytics, facebook items. You can add more URL's that you need to by checking what is in your console.log for errors.



Posted on

April 27, 2021

Submit a Comment

Your email address will not be published. Required fields are marked *