Reject Requests for Unknown Host Names
Returns an error for requests whose Host header is not your site's domain, which blocks host header injection tricks (such as poisoned password reset links) and junk traffic aimed at your server's IP.
Opens WPIDE on
Code
// Extra host names allowed besides the site and home URL hosts.
$wpide_allowed_hosts = array();
add_action( 'init', function () use ( $wpide_allowed_hosts ) {
if ( ( defined( 'WP_CLI' ) && WP_CLI ) || wp_doing_cron() || empty( $_SERVER['HTTP_HOST'] ) ) {
return;
}
$host = strtolower( preg_replace( '/:\d+$/', '', sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) ) );
$allowed = array_merge( $wpide_allowed_hosts, array( wp_parse_url( home_url(), PHP_URL_HOST ), wp_parse_url( site_url(), PHP_URL_HOST ) ) );
$allowed = array_map( 'strtolower', array_filter( $allowed ) );
foreach ( $allowed as $name ) {
$allowed[] = 0 === strpos( $name, 'www.' ) ? substr( $name, 4 ) : 'www.' . $name;
}
if ( ! in_array( $host, $allowed, true ) ) {
status_header( 400 );
nocache_headers();
exit( 'Unknown host.' );
}
}, 0 );
Notes
Add every domain and subdomain that legitimately points at this site (staging, www, mapped domains) to $wpide_allowed_hosts.
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.