How to restrict access by IP address to specific path with Tomcat?

1k Views Asked by At

Dears,

Can anyone help on restricting the access to a specific path on the web application by IP address?

Currently I have applied RemoteAddrValve and it perfectly works for all web application directory. Actually I need to apply this only on specific path.

It is highly appreciated if someone can help on this.

<Context><WatchedResource>WEB-INF/web.xml</WatchedResource><Valve className="org.apache.catalina.valves.RemoteAddrValve" deny="some IPs" denyStatus="404"/></Context>
1

There are 1 best solutions below

0
On

As you mentioned, the RemoteAddrValve is too broad for your need. The solution is to use the RewriteValve matching both conditions (IP + path) and for the rule, denying the traffic. Don't forget to read the Tomcat doc to learn more on rewrites.

First, add the adequate valve in your Host definition in server.xml :

<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />

Supposing your host name is the default one (localhost), you need to create $CATALINA_BASE/conf/Catalina/localhost/rewrite.config file with this content :

RewriteCond %{REMOTE_ADDR} bad.ip.addr.ess
RewriteRule ^/forbidden-path(.*)$ / [F]

The F flag will send a 403 Forbidden HTTP code. You can change the rule as you want, for example to redirect to a login page (flag R).

If your website is exposed on Internet, don't forget that anyone could use a proxy to hide its real IP address. If you're using a reverse-proxy in front of your Apache, you might need to configure it adequately not to loose the user's real IP of your Tomcat could only see your reverse proxy IP.