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
- Log in to your server by SSH as root.
- Check that Tomcat is running and answers on port 8080.
This asks Tomcat for its page headers. A reply starting with HTTP means it works.curl -I http://127.0.0.1:8080/ - Make sure the proxy modules are on. On many systems:
This turns on the modules. On servers with WHM and EasyApache, install the modules from EasyApache 4 instead.a2enmod proxy proxy_http rewrite - Open the settings (virtual host) file for your site.
- Add these lines inside the virtual host block:
ProxyPreserveHost On ProxyPass / http://127.0.0.1:8080/ ProxyPassReverse / http://127.0.0.1:8080/ProxyPasssends requests to Tomcat.ProxyPassReversefixes addresses in the replies. - To send only one path to Tomcat, use it like this:
This sends only addresses starting withProxyPass /app http://127.0.0.1:8080/app ProxyPassReverse /app http://127.0.0.1:8080/app/app. - To use mod_rewrite instead, add:
TheRewriteEngine On RewriteRule ^/(.*)$ http://127.0.0.1:8080/$1 [P,L]Pflag means proxy. This sends all requests to Tomcat. - Test the settings.
It should sayapachectl configtestSyntax OK. - Reload Apache.
On some systems the service is namedsystemctl reload httpdapache2.
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 configtestbefore reload. - Back up settings first.