HTTP Security Headers in wp-config
题
Is there a way to place the HTTP Security Headers in wp-config.php
instead of in .htaccess
or functions.php
? If so, what is the format?
解决方案
The .htaccess
file is read by the Apache server software before it even hands over to WordPress to generate a page. It is by far the best place to have your security headers.
That said, WordPress does have a class to modify the headers before they are send to the browser. This class contains a filter which you could use in a plugin. Beware that this filter might be bypassed if your page is served by a caching plugin (or some server level form of caching).
The wp-config.php
file has a fairly narrow scope, as you can see in the codex. Defining security headers there is not among the possibilities.
Bottom line: yes, there are some ways to set security headers within WordPress, but make sure your .htaccess
is in order.
其他提示
The wp-config.php
file is not a good place to put the headers but in case that you do not have access to .htaccess
or you are in Nginx server that you are not allowed to modify config, you can put this in your theme's functions.php
or a plugin:
Modifying WP headers via wp_headers filter
function additional_headers( $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 "https://example.com") microphone=() camera=()';
$headers['Content-Security-Policy'] = 'script-src "self"';
$headers['X-Frame-Options'] = 'SAMEORIGIN'; }
return $headers;
}
add_filter( 'wp_headers', 'additional_securityheaders' );