How to block unwanted hosts in .htaccess?

561 Views Asked by At

These .htaccess rules work:

<RequireAll>
Require all granted
Require not ip 1.22.333.444
.
.
.
</RequireAll>

These .htaccess rules don't work:

<RequireAll>
Require all granted
.
.
.
Require not host bad_host
</RequireAll>

These .htaccess rules don't work as well:

<IfModule mod_rewrite.c>
RewriteCond %{REMOTE_HOST} (163data|amazonaws|colocrossing|poneytel) [NC]
RewriteRule .* - [F,L]
</IfModule>

I wrote into the .htaccess file at the top:

HostnameLookups On

The result was an error message, because this command is not allowed in .htaccess. So I removed this statement.

In Apache, there is a "remote_host" corresponds to a certain IP. I want tp prevent unwanted hosts to visit my site, such as spammers or such which generate much useless traffic in my site.

What is wrong in the code example above?

1

There are 1 best solutions below

1
On

HostnameLookups needs to be set in the server config for the REMOTE_HOST server variable to be set. This cannot be set in .htaccess (as you have found). This is Off by default and is often permanently disabled on shared hosts for performance reasons.

However, Require [not] host bad_host is not dependent on HostnameLookups being set, so should still work (providing the host has not disabled this in some way). Note that bad_host allows partial matches, matched from the end and only complete host segments are matched. eg. ample.com and foo.bar.example will not match foo.bar.example.com, but example.com and bar.example.com will.

Note that Require [not] host causes Apache to perform a "double reverse DNS lookup". First the hostname is looked up (reverse DNS lookup) from the client IP address and then there is a forward lookup on the hostname to check that the IP address matches. If this does not match then the check fails.

Maybe a forward-dns only check is sufficient (requires Apache 2.4.19)? This only performs the reverse DNS lookup to get the hostname. The hostname is not validated.

For example:

Require not forward-dns example.com