If you have sensitive information on your website, or certain parts of it, then it might be a good idea to create an IP whitelist who can access that information. Otherwise, your website might become vulnerable to malicious attackers. Here’s how to whitelist IP in Apache.
How to Whitelist IP in Apache
Here are the steps to whitelist IP in Apache. Before proceeding, please ensure you have enabled .htaccess (mod_rewrite) in your Apache web server. Here are the steps to do it:
Place your .htaccess file in the root document folder of your website (/var/www/html)
1. Open .htaccess file
Open .htaccess file using a text editor. It is generally located at /var/www/html.
$ sudo vim /var/www/html/.htaccess
2. Whitelist IP
Let’s say you want to restrict your entire website to a couple of known IPs (220.127.116.11 and 18.104.22.168) then add the following code to your .htaccess file.
<Location /> Order deny,allow Allow from 22.214.171.124 Allow from 126.96.36.199 </Location>
<Location /> Require IP 188.8.131.52 Require IP 184.108.40.206 </Location>
Let’s say you want to restrict only a specific directory (e.g /admin) to a couple of known IPs (220.127.116.11 and 18.104.22.168) then change the Location block as shown.
<Location /admin> Order deny,allow Allow from 22.214.171.124 Allow from 126.96.36.199 </Location>
<Location /admin> Require IP 188.8.131.52 Require IP 184.108.40.206 </Location>
The above codes will restrict your website and directories to only the specific URLs you want to allow.
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]