Block Fake Googlebot Visits
Checks visitors that claim to be Googlebot with a reverse DNS lookup and blocks the impostors, which are usually scrapers or vulnerability scanners.
Opens WPIDE on
Code
add_action( 'init', function () {
$agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? (string) $_SERVER['HTTP_USER_AGENT'] : '';
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) $_SERVER['REMOTE_ADDR'] : '';
if ( false === stripos( $agent, 'Googlebot' ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
return;
}
$key = 'wpide_gbot_' . md5( $ip );
$genuine = get_transient( $key );
if ( false === $genuine ) {
$host = gethostbyaddr( $ip );
$forward = array();
if ( $host && preg_match( '/\.(googlebot|google)\.com$/i', $host ) ) {
if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
$forward = (array) gethostbynamel( $host );
} else {
foreach ( (array) dns_get_record( $host, DNS_AAAA ) as $record ) {
if ( ! empty( $record['ipv6'] ) ) {
$forward[] = inet_ntop( inet_pton( $record['ipv6'] ) );
}
}
$ip = inet_ntop( inet_pton( $ip ) );
}
}
$genuine = in_array( $ip, $forward, true ) ? 'yes' : 'no';
set_transient( $key, $genuine, DAY_IN_SECONDS );
}
if ( 'no' === $genuine ) {
status_header( 403 );
exit( 'Forbidden' );
}
}, 0 );
Notes
The DNS check runs once per IP per day and adds a short delay to that first request.
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.