Block direct ip access to your server in Apache 2.4

Let’s say you have:

  • A server with an ip address (like xxx.xxx.xxx.xxx)
  • A domain name (like example.com)

And you want to be able to reach your web server (Apache 2.4 in this case) via your domain name (example.com) but you want to block access via ip address (so that when you type xxx.xxx.xxx.xxx in the address bar, it doesn’t work).

  • Connect via SSH to your server.
  • Create a new config file in the sites-available directory:
    sudo nano /etc/apache2/sites-available/direct.conf

Now type the following lines

<VirtualHost *:80>
    ServerName xxx.xxx.xxx.xxx
    Redirect 403
    DocumentRoot /dev/null
</VirtualHost>
  • Save the file
  • Type sudo a2ensite direct
  • Now restart your server: sudo apache2 restart

Done. You won’t be able to access your website using the IP address of your server.

If you want to disable this particular site configuration, just type sudo a2dissite direct and restart the server (sudo apache2 restart)

EDIT:

You might have to use

Redirect 403 /

As pointed out by Chris (thanks for letting me know).