Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Running Tomcat Behind Apache with mod_rewrite and mod_proxy

This guide shows how to let Apache pass visitors on to a Tomcat Java application. It needs root access to a VPS or dedicated server.

General2 min read9 steps

Key words first

  • Apache is the program that serves most web pages on port 80 and 443.
  • Tomcat is a program that runs Java web applications. It usually listens on port 8080.
  • mod_proxy is an Apache add-on that forwards requests to another program. Think of a receptionist who passes your call to the right person.
  • mod_rewrite is an Apache add-on that changes web addresses by rules.

Visitors then use a clean address like https://example.com/, without :8080 at the end.

Warning: Back up your Apache settings before you change them. A typing mistake can stop your sites.

Steps

  1. Log in to your server by SSH as root.
  2. Check that Tomcat is running and answers on port 8080.
    curl -I http://127.0.0.1:8080/
    This asks Tomcat for its page headers. A reply starting with HTTP means it works.
  3. Make sure the proxy modules are on. On many systems:
    a2enmod proxy proxy_http rewrite
    This turns on the modules. On servers with WHM and EasyApache, install the modules from EasyApache 4 instead.
  4. Open the settings (virtual host) file for your site.
  5. Add these lines inside the virtual host block:
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/
    ProxyPass sends requests to Tomcat. ProxyPassReverse fixes addresses in the replies.
  6. To send only one path to Tomcat, use it like this:
    ProxyPass /app http://127.0.0.1:8080/app
    ProxyPassReverse /app http://127.0.0.1:8080/app
    This sends only addresses starting with /app.
  7. To use mod_rewrite instead, add:
    RewriteEngine On
    RewriteRule ^/(.*)$ http://127.0.0.1:8080/$1 [P,L]
    The P flag means proxy. This sends all requests to Tomcat.
  8. Test the settings.
    apachectl configtest
    It should say Syntax OK.
  9. Reload Apache.
    systemctl reload httpd
    On some systems the service is named apache2.
Tip: Keep port 8080 closed to the outside world in your firewall. Then visitors can only reach Tomcat through Apache.

Quick recap

  • Apache can forward visitors to Tomcat with mod_proxy.
  • Use ProxyPass and ProxyPassReverse lines.
  • mod_rewrite with the P flag does the same by rule.
  • Run apachectl configtest before reload.
  • Back up settings first.