Block TRACE, TRACK and Other Unusual HTTP Methods
Answers requests that use HTTP methods WordPress never needs (such as TRACE, TRACK, CONNECT or DEBUG) with a 405 error before any page is built.
Opens WPIDE on
Code
// Methods that are allowed.
$wpide_allowed_methods = array( 'GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'PATCH', 'DELETE' );
add_action( 'init', function () use ( $wpide_allowed_methods ) {
if ( ( defined( 'WP_CLI' ) && WP_CLI ) || empty( $_SERVER['REQUEST_METHOD'] ) ) {
return;
}
$method = strtoupper( sanitize_key( $_SERVER['REQUEST_METHOD'] ) );
if ( ! in_array( $method, $wpide_allowed_methods, true ) ) {
status_header( 405 );
header( 'Allow: ' . implode( ', ', $wpide_allowed_methods ) );
exit;
}
}, 0 );
Notes
GET, POST, HEAD, OPTIONS, PUT, PATCH and DELETE stay allowed because the REST API uses them.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.