How to Restrict Directory Access by IP in Apache?
This article provides a quick overview and step-by-step guide on how
to secure a specific directory on your Apache web server by limiting
access to authorized IP addresses. You will learn how to configure the
.htaccess file or the main Apache configuration file using
the Require directive. By implementing these restrictions,
you can effectively shield sensitive directories from unauthorized
external traffic.
Prerequisites
Before making changes, ensure you have access to either your Apache
server’s main configuration file (usually httpd.conf or
apache2.conf) or have .htaccess overrides
enabled for the target directory. You will also need the specific IP
addresses or IP ranges you wish to allow or block.
Method 1: Using the Apache Configuration File (Recommended)
Modifying the main server configuration is the most secure and efficient method because Apache does not have to read a file on every single page request.
- Open your Apache configuration file in a text editor.
- Locate or create a
<Directory>block pointing to your specific folder path. - Use the
Requiredirective to control access.
<Directory "/var/www/html/secure-directory">
Options Indexes FollowSymLinks
AllowOverride None
# Block all traffic by default, allow specific IPs
Require ip 192.168.1.50
Require ip 10.0.0.0/24
</Directory>In this example, only the single IP 192.168.1.50 and the
subnet 10.0.0.0/24 are granted access. All other traffic is
automatically denied.
Method 2: Using a .htaccess File
If you do not have administrative access to the main server
configuration files (common in shared hosting environments), you can
achieve the same result using a .htaccess file placed
directly inside the directory you want to protect.
- Create or edit a file named
.htaccessin the specific directory. - Add the following lines to the file:
# Block all traffic by default
Require all denied
# Explicitly allow trusted IP addresses
Require ip 192.168.1.50
Require ip 203.0.113.0/24Allowing All Except Specific IPs (Blacklisting)
If your goal is to let everyone access the directory except for a few
malicious or unwanted IP addresses, reverse the logic using the
not operator:
<Directory "/var/www/html/public-directory">
<RequireAll>
Require all granted
Require not ip 198.51.100.7
</RequireAll>
</Directory>Applying the Changes
If you updated the main Apache configuration file, you must restart or reload the Apache service for the changes to take effect. Run one of the following commands in your terminal depending on your operating system:
- Ubuntu/Debian:
sudo systemctl reload apache2 - CentOS/RHEL:
sudo systemctl reload httpd
Changes made to a .htaccess file apply instantly and do
not require a server reload.