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. It can be difficult to whitelist individual IPs. Luckily, Apache allows you to whitelist IP ranges. Here’s how to whitelist IP range in Apache.
How to Whitelist IP Range 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 Range
Let’s say you want to restrict your entire website to a couple of known IP ranges (18.104.22.168-22.214.171.124 and 126.96.36.199-188.8.131.52) then add the following code to your .htaccess file. We will use the CIDR notation to specify IP ranges. You can use an online tool to easily get the CIDR notation for your IP range.
<Location /> Order deny,allow Allow from 184.108.40.206/24 Allow from 220.127.116.11/24 </Location>
<Location /> Require IP 18.104.22.168/24 Require IP 22.214.171.124/24 </Location>
Let’s say you want to restrict only a specific directory (e.g /admin) to a couple of known IP ranges (126.96.36.199-188.8.131.52 and 184.108.40.206-220.127.116.11) then change the Location block as shown.
<Location /admin> Order deny,allow Allow from 18.104.22.168/24 Allow from 22.214.171.124/24 </Location>
<Location /admin> Require IP 126.96.36.199/24 Require IP 188.8.131.52/24 </Location>
The above codes will restrict your website and directories to only the specific IP ranges 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]