Sometimes you may need to restrict access to URL by IP. Apache allows you to limit access to URL by single IP, multiple IP addresses and even IP address ranges. In this article, we will look at how to restrict access to URL by IP. You can use these steps to secure URL in Apache.
Apache Restrict Access to URL by IP
Here are the steps to restrict access to URL by IP.
1. Open Apache Configuration File
Apache configuration file is located at one of the following locations, depending on your Linux distribution.
Open terminal and run the following command to open Apache configuration page.
$ sudo vi /etc/httpd/conf/httpd.conf
If you make changes in Apache server configuration file, it will be applicable for all websites/domains that you run on your Apache web server.
Apache Restrict Access by IP in Virtual Host
If you are running multiple websites on Apache server, using virtual host, then open the virtual host configuration file of the website (e.g www.website.com) for which you want to deny access to IP. Let’s say your virtual host configuration file is located at /etc/apache2/sites-enabled/website.conf
$ sudo vi /etc/apache2/sites-enabled/website.conf
Also read : How to Enable HTTP2 in Apache
2. Restrict Access by IP
Let us assume you want to limit access to /product.html URL by IP 184.108.40.206. Once you have opened the appropriate configuration file, look for <Location> tag for the above URL.
Apache provides Deny directive to block one or more IP addresses. Add the following line in Location tag
Your Location tag will look something like the following
<Location /product.html> ... Deny 220.127.116.11 ... </Location>
If you want to block IP from accessing a specific directory such as /admin, then add the above Deny directive in location block of /admin subfolder.
<Location /admin> ... Deny 18.104.22.168 ... </Location>
Also read : How to Enable Apache Server Status Dashboard
Apache Limit Access by multiple IP
If you want to limit access to multiple IPs, add separate Deny directives for each IP.
In the following example, we limit access to IPs 22.214.171.124 and 126.96.36.199
<Location /product.html > ... Deny 188.8.131.52 Deny 184.108.40.206 ... </Location>
If you want to restrict access by IP range such as 220.127.116.11-18.104.22.168 then you can do it by using CIDR notation of this IP range. Here’s the configuration to restrict access from above IP range.
<Location /product.html > ... Deny 22.214.171.124/24 ... </Location>
Also read : How to Disable HTTP Options Methods in Apache
3. Restart Apache web server
Restart Apache web server to apply changes.
# service httpd restart OR # systemctl restart httpd OR # sudo service apache2 restart
Now when a user tries to access your URL or directory from blocked IP address, they will get a “403: Access Forbidden” response.