"IT is like a shark, if you stop moving you will die!"

Vladimir Dejanović

How to put Java application behind Apache HTTP server

29 Mar 2018     2 min read

In the "old days" it was very common thing to put Apache HTTP server in front of your Java application server, or Java application it self.

Reason behind it was very simple, caching could be added in easy way, also load balancing could be added, and on top of this static content could be served by Apache HTTP while all other requests could be served by Java application.

apache

Although this setup isn't new, I still encounter it on regular basis, and see that a lot of people still have issues of how to set this up.

Let assume that you want to intercept all request to static files and serve them from hard drive, while all other requests need to be passed to Tomcat.

After you install Apache HTTP server, next thing is to add specific modules

  • mod_proxy
  • mod_proxy_http
  • mod_rewrite

On some systems this can be done in this way

$ a2enmod rewrite
$ a2enmod proxy
$ a2enmod proxy_http

After this configuration file of Apache HTTP server need to be updated. Locate conf file

<VirtualHost *:80>
   .......
</VirtualHost>

Add rewrite rule that will intercept all calls to static and change them to be served from hard disk

# rewrite from static to it shark static
RewriteEngine on
RewriteRule ^/static/(.+) /itshark/$1 [L,PT]

Alias "/itshark" "/location/on/disk"

With this we say to Apache HTTP that any URL request which starts with /static should be rewritten to /itshark/

After which we say that all request for /itshark should be served from /location/on/disk. We also need to add this part into config in order for Apache HTTP to be able to access it.

<Directory "/location/on/disk">
        Options None
        AllowOverride None
        Require all granted
</Directory>

Depending on your OS and Apache HTTP version this should be either in main conf file (for example: /etc/apache2/apache2.conf) or in conf file for VirtualHost (for example: /etc/apache2/sites-enabled/000-default.conf).

File names and location depend on system and Apache HTTP version

Now all that is left is to send all rest traffic to Apache Tomcat.

In order to do so we need to add this to VirtualHost conf file

ProxyPassMatch ^/(itshark)/.*$ !
ProxyPass / http://localhost:8080/ connectiontimeout=300 timeout=300 retry=3
ProxyPreserveHost On
ProxyVia On 

And that it is. All request to /static/ will end up in /location/on/disk/, while everything else will be sent to Apache Tomcat.