Adrian
Courrèges

IP Range Filter with Apache or Tomcat

Sometimes it can be useful to restrict access to a server depending on the IP address of the client. When you’re developing an application and you wish to run some tests over the internet you don’t want everybody to have access to the documents or services you expose to the network.

Here is a way to allow access only from a certain range of IP addresses. For the following let’s assume that you want to allow only 12.34.56.78 and LAN adresses 192.168.1.* to access the server

For ApacheApache logo

If you want to protect the documents of a directory, a simple .htaccess file is enough. You just need to create a file named “.htaccess” in the directory you want to protect, with the following content:

.htaccess
1
2
3
4
Order Deny,Allow
Deny from all
Allow from 12.34.56.78
Allow from 192.168.1.0/24

For TomcatTomcat logo

Tomcat does not understand .htaccess files.
In my case I wanted to restrict the access to the entire webserver. This can be done by modifying the context configuration.

Edit the file context.xml located in the conf directory of your Tomcat installation. You just need to add a valve within <Context>.

context.xml
1
2
3
4
5
6
7
8
<Context>

    [...]

    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
            allow="12\.34\.56\.78,192\.168\..*" />

</Context>

Note that the syntax is quite different from the one you would expect especially for regular expressions.
Tomcat should now reply with a 403 forbidden answer to unauthorized clients.

Don’t forget to restart Tomcat for the changes to take effect.

Comments