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 https://securityheaders.com/ using the following must use plugin.

<?php

/*
Plugin Name: Additional Security Headers
Plugin URI: https://snippets.wpcms.ninja
Description: This adds additional security headers to the front end of the website that can help protect people browsing.
Author: billiardgreg
Author URI: https://wpcms.ninja
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' https://fonts.gstatic.com data:;";
$headers['Content-Security-Policy'] .= "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;";
$headers['Content-Security-Policy'] .= "frame-src 'self' https://www.facebook.com; ";
$headers['Content-Security-Policy'] .= "script-src 'self' 'unsafe-inline' https://www.google-analytics.com https://connect.facebook.net; ";
$headers['Content-Security-Policy'] .= "script-src-elem 'self' 'unsafe-inline' https://www.google-analytics.com https://connect.facebook.net; ";
$headers['Content-Security-Policy'] .= "connect-src 'self' https://www.facebook.com https://www.google-analytics.com;";
$headers['Content-Security-Policy'] .= "img-src 'self' https://s.w.org https://www.google-analytics.com https://www.facebook.com http://www.w3.org https://secure.gravatar.com 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.

 

Skills

Posted on

April 27, 2021

Submit a Comment

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