Sometimes, you may need to allow access to multiple IP address ranges to your website, or specific pages on your site. .htaccess file allows you to do that without accessing Apache server config files. Here’s how to allow multiple IP address range using .htaccess.
How to Allow Multiple IP Address Range using .htaccess
Here are the steps to allow multiple IP address range using .htaccess. Before you proceed, please ensure that you have enabled mod_rewrite (.htaccess) in your Apache web server. Here are the steps to do it in:
1. Open .htaccess file
Open the .htaccess file in a text editor. You will generally find it at /var/www/html
$ sudo vim /var/www/html/.htaccess
2. Allow Multiple IP Address Range
Let’s say you want to allow multiple IP addresses access to your website and block everyone else. Then add the following code to your .htaccess file. You can put it in directory or location directive, or any other line.
# Apache v2.2 Order deny,allow Deny from all Allow from 126.96.36.199 188.8.131.52 # Apache v2.4 Require all denied Require ip 184.108.40.206 220.127.116.11
If you want to allow an IP address range (192.168.0.1 – 192.168.0.255), use the CIDR notation to specify the IP range.
# Apache v2.2 Order deny,allow Deny from all Allow from 192.168.0.0/24 # Apache v2.4 Require all denied Require ip 192.168.0.0/24
If you want to allow multiple IP address ranges (192.168.0.1 – 192.168.0.255, 18.104.22.168 – 22.214.171.124), use the CIDR notation to specify the IP ranges.
# Apache v2.2 Order deny,allow Deny from all Allow from 192.168.0.0/24 126.96.36.199/24 # Apache v2.4 Require all denied Require ip 192.168.0.0/24 188.8.131.52/24
Please Note: If you put the above code in the main .htaccess file located in your website root (/var/www/html) it will be applicable for all pages on your website. If you want to allow access to only a specific directory, then create a blank .htaccess file in that directory and add the above lines in that file.
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]