# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: hardening, http, headers
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/sec-validate-host-header/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Reject Requests for Unknown Host Names" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
