Sometimes, you want to block people from accessing your website directly using its IP address. In that case, you can setup your virtual hosts such that people can access your website only via its domain name and not IP. Let’s take a look at how to prevent direct IP access in Apache.
How to Prevent Direct IP Access in Apache
Here are the steps to prevent direct IP access in Apache.
1. Open Apache config file
Open Apache config file in a text editor. You will find it at one of the following locations:
$ sudo vim /etc/apache2/httpd.conf
2. Block Direct IP Access
Let’s say you have a virtual host for your domain example.com and want to block people from accessing it via your ip 220.127.116.11 then add the following virtual hosts to your Apache config file.
<VirtualHost example.com:80> ServerName example.com ServerAlias www.example.com DocumentRoot /home/rotate/public_html ServerAdmin email@example.com UseCanonicalName Off </VirtualHost> NameVirtualHost example.com:80 <VirtualHost 18.104.22.168:80> ServerName 22.214.171.124 Redirect 403 / ErrorDocument 403 "No direct IP access not allowed." DocumentRoot /usr/local/apache/htdocs ServerAdmin firstname.lastname@example.org UseCanonicalName Off UserDir disabled </VirtualHost>
The key is to create a second virtual host that uses your IP address and add the directives
UseCanonicalName Off and
UserDir disabled and also return “403: access forbidden” response.
Please Note: If you have setup separate virtual host files for each domain in Apache, then update the <VirtualHost> block in their respective files, with the ones shown above.
3. Restart Apache web server
Restart Apache web server to apply changes
$ sudo /etc/init.d/apache2 start [Debian or Ubuntu] # sudo apachectl restart [RHEL, CentOS or Fedora]
That’s it! Now Apache will ensure that users can access your website only via its domain name and not IP address.