Apache: restrict access based on IP address to selected directories

apacheThe Apache web server lets you control access based on various conditions. For example, suppose you want to restrict access to http://subdomain.domain.com/ (mapped to the /var/www/subdomain directory) from the 192.168.1.0/24 network (within an intranet).

Apache provides access control based on client hostname, IP address, or other characteristics of the client request using mod_authz_core in Apache 2.4 (or mod_authz_host / mod_access in legacy Apache 2.2).

Apache 2.4 (recommended on modern Ubuntu / RHEL): use the Require ip directive inside your <VirtualHost> or <Directory> block:

<Directory /var/www/subdomain/restricted>
    Require ip 192.168.1.0/24
</Directory>

You can combine multiple IPs or subnets with spaces or multiple Require ip lines. To allow only one specific admin IP, use Require ip 203.0.113.10 (and pair it with HTTPS or a VPN when connecting across untrusted networks).

Legacy Apache 2.2 equivalent:

<Directory /var/www/subdomain/restricted>
    Order deny,allow
    Deny from all
    Allow from 192.168.1.0/24
</Directory>

Validate syntax before reloading Apache:

sudo apache2ctl configtest && sudo systemctl reload apache2

Reference: cyberciti.biz

Comments are Disabled