Created
May 25, 2023 20:51
-
-
Save lukecav/a934c3097478e2f726fa9d2beda8eefb to your computer and use it in GitHub Desktop.
Add HTTP security headers in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function add_security_headers($headers) { | |
// Add X-XSS-Protection header | |
$headers['X-XSS-Protection'] = '1; mode=block'; | |
// Add X-Content-Type-Options header | |
$headers['X-Content-Type-Options'] = 'nosniff'; | |
// Add X-Frame-Options header | |
$headers['X-Frame-Options'] = 'SAMEORIGIN'; | |
// Add Content-Security-Policy header | |
$headers['Content-Security-Policy'] = "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';"; | |
// Add Strict-Transport-Security header | |
$headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains; preload'; | |
return $headers; | |
} | |
add_filter('wp_headers', 'add_security_headers'); |
This code snippet adds the following security headers:
X-XSS-Protection: Enables the browser's Cross-Site Scripting (XSS) filter.
X-Content-Type-Options: Prevents MIME type sniffing.
X-Frame-Options: Restricts the site from being displayed within a frame.
Content-Security-Policy: Defines a content security policy to restrict resource loading.
Strict-Transport-Security: Enforces the use of HTTPS by instructing the browser to always access the site via a secure connection.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.wordpress.org/reference/hooks/wp_headers/