最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

HTTP Security Headers in wp-config

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Aug 2, 2017 at 17:02 cjbj 15k16 gold badges42 silver badges89 bronze badges asked Aug 2, 2017 at 16:14 JorgeJorge 233 bronze badges 2
  • This doesn't sound like a very good idea from the point of security. Could you explain a little bit more what you are trying to achieve by doing this. – cjbj Commented Aug 2, 2017 at 16:21
  • I want to create a script to automatically check if these headers are set (among other security recommendations) and if not, set them. The wp-config.php file seems simpler to deal with compared to .htaccess and funtions.php. Also, the .htacess may be protected. I know there are plugins already for this but I would like to do this at least as a learning exercise. – Jorge Commented Aug 2, 2017 at 16:26
Add a comment  | 

2 Answers 2

Reset to default 1

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") microphone=() camera=()';
  $headers['Content-Security-Policy']     = 'script-src "self"';
  $headers['X-Frame-Options']             = 'SAMEORIGIN';   }

  return $headers; 
}
  
add_filter( 'wp_headers', 'additional_securityheaders' );

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论