.htaccess block access when HTTP_HOST is IP (Security)

Solution 1:

You don't need to check the Host header for specific IPs, just check for any Host that starts with a digit. For example, at the top of your .htaccess file:

RewriteCond %{HTTP_HOST} ^\d
RewriteRule .* - [F]

You don't need the L flag with F - it is implied.

You also don't need the additional <IfModule mod_rewrite.c> wrappers. Just leave the WordPress one as it is. (Although that isn't strictly required either.)

However, these type of blocks should ideally be performed at the server/vitualhost level, not in .htaccess. Configure a default <VirtualHost> that traps these undesirable IP requests.

For example, assuming you are only using name-based VirtualHosts then you can configure a default VirtualHost (that must occur before all other VirtualHosts) of the form:

# Catch all other requests for non-specific hosts. eg IP address access
<VirtualHost _default_>
  ServerName default.example.com
  <Location />
  Require all denied
  </Location>
</VirtualHost>

This catches all requests that do not map to any other "named" Virtual Host. _default_ is simply an alias for *. As noted above, this <VirtualHost> container must occur before all other <VirtualHost> containers in your server config. The fact that it is defined first is what makes it the "default".

The ServerName directive should be defined as anything other than a real server name on your system. It can be omitted, but the server will only attempt to calculate it, which could prove unreliable.

This prevents your actual Virtual Hosts (that serve your website) from having to deal with these other requests.


# deny all POST requests

That seems a little extreme! I'm surprised your site still works?