Apache: Restrict access to specific source IP inside virtual host
I have several named virtual hosts on the same apache server, for one of the virtual host I need to ensure only a specific set of IP addresses are allowed to access.
Please suggest the best way to do this. I have looked at mod_authz_hosts module but it does not look like I can do it inside virtual host.
Solution 1:
The mod_authz_host
directives need to be inside a <Location>
or <Directory>
block but I've used the former within <VirtualHost>
like so for Apache 2.2:
<VirtualHost *:8080>
<Location />
Order deny,allow
Deny from all
Allow from 127.0.0.1
</Location>
...
</VirtualHost>
Reference: https://askubuntu.com/questions/262981/how-to-install-mod-authz-host-in-apache
Solution 2:
For Apache 2.4, you would use the Require IP directive. So to only allow machines from the 192.168.0.0/24 network (range 192.168.0.0 - 192.168.0.255)
<VirtualHost *:80>
<Location />
Require ip 192.168.0.0/24
</Location>
...
</VirtualHost>
And if you just want the localhost machine to have access, then there's a special Require local directive.
The local provider allows access to the server if any of the following conditions is true:
- the client address matches 127.0.0.0/8
- the client address is ::1
- both the client and the server address of the connection are the same
This allows a convenient way to match connections that originate from the local host:
<VirtualHost *:80>
<Location />
Require local
</Location>
...
</VirtualHost>
Solution 3:
If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):
Order deny,allow
Deny from all
Allow from 10.0.0.1
You can even specify a subnet
Allow from 10.0.0
Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.
Solution 4:
In Apache 2.4, the authorization configuration syntax has changed, and the Order
, Deny
or Allow
directives should no longer be used.
The new way to do this would be:
<VirtualHost *:8080>
<Location />
Require ip 192.168.1.0
</Location>
...
</VirtualHost>
Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2