When running a WordPress site, you probably already have far too many plugins to keep track of. You could use a full-featured plugin to add security headers, but why add the extra overhead if you don't have to?
In this article, we'll show you how to add security headers from inside Atomic or optionally by using a quick drop-in plugin for WordPress sites not hosted at Pagely.
Setting Security Headers at the ARES Gateway Level (Recommended for Pagely Sites)
If you're a Pagely customer, we recommend setting these headers from within the ARES gateway for best performance. For more information, see our article on setting response headers in Atomic.
WordPress Security Headers Example Code (Works on All WordPress Sites)
Headers can be easily added to WordPress sites with just a few lines of code.
Here's an example of what those few lines look like:
function pagely_security_headers( $headers ) {
$headers['X-XSS-Protection'] = '1; mode=block';
$headers['X-Content-Type-Options'] = 'nosniff';
$headers['X-Content-Security-Policy'] = 'default-src \'self\'; script-src \'self\';';
return $headers;
}
add_filter( 'wp_headers', 'pagely_security_headers' );
In the example above, all we're doing is using a hook that already exists inside WordPress to handle a few additional security headers. By using the wp_headers filter, we can easily add or override any headers before the page is rendered.
Creating a Drop-In Plugin to Handle WordPress Headers
When modifying default WordPress behavior, it's almost always best to use single-use plugins. This ensures that your changes persist if an update occurs or you switch themes.
That's why a drop-in plugin is perfect for things like changing security headers. You can easily make a few tweaks that persist regardless of other plugins and themes, without the extra overhead of using a full-featured security headers plugin.
To make this solution into a drop-in WordPress plugin, just create a file inside your wp-content (we've named ours pagely-security-headers.php) with the following content:
<?php
/*
Plugin Name: Pagely Security Headers
Plugin URI: https://support.pagely.com
Description: A drop-in plugin by Pagely to add security headers.
Author: JeffMatson, Pagely
Version: 0.1
Author URI: https://pagely.com
*/
function pagely_security_headers( $headers ) {
$headers['X-XSS-Protection'] = '1; mode=block';
$headers['X-Content-Type-Options'] = 'nosniff';
$headers['X-Content-Security-Policy'] = 'default-src \'self\'; script-src \'self\';';
return $headers;
}
add_filter( 'wp_headers', 'pagely_security_headers' );
From there, all that's left to do is modify it to suit the headers that you want to insert, then activate it!