Force Apache show a 403 error when accessing via IP address

Let’s say we have a few websites hosted in our machine, but we need them to process requests only via a name service; not when accessed via IP address. Very common behavior in shared hosting systems.

A real time saving tip, and it only needs a couple of lines of code. For this purpose we tested it on an Apache 2.4 server running under a CentOS system.

To achieve this we only need to make a new file (e. g. default.conf under the /etc/httpd/conf.d directory) containing the following lines:

<VirtualHost _default_:80>
   UseCanonicalName Off
   Redirect 403 /

Of course we should run a reload to apply the changes we made on the service:

systemctl reload httpd

And that’s literally all, from here on out when anyone access the webserver through its IP address, the only thing that will show up is a beautiful 403 error message like this one (which is what we ever intended, right?) as long as you do not tune this up to show anything else or even a custom error message:


You don't have permission to access / on this server.