How to Prevent Direct IP Access in Apache


block direct ip access apache

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:

  • /etc/apache2/httpd.conf
  • /etc/apache2/apache2.conf
  • /etc/httpd/httpd.conf
  • /etc/httpd/conf/httpd.conf

 


$ 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 54.54.54.54 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 me@example.com
    UseCanonicalName Off
</VirtualHost>

NameVirtualHost example.com:80
<VirtualHost 54.54.54.54:80>
    ServerName 54.54.54.54
    Redirect 403 /
    ErrorDocument 403 "No direct IP access not allowed."
    DocumentRoot /usr/local/apache/htdocs
    ServerAdmin me@example.com
    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.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!