NGINX as Proxy to Tomcat

To make Tomcat accessible via the domain name tomcat.sampledomain.com, you need to configure both Tomcat and Nginx appropriately. This setup involves modifying the server.xml file in Tomcat to include a new connector and updating Nginx's site configuration to proxy requests to Tomcat.

Configure Tomcat

Add a new connector to the server.xml file for HTTPS redirection through the proxy. Place this configuration below the existing connector for port 8080:

<!-- Existing Connector on Port 8080 -->
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />

<!-- New Connector for Proxy -->
<Connector port="9090" protocol="HTTP/1.1"
           connectionTimeout="20000" maxThreads="2000"
           scheme="https" proxyPort="443" redirectPort="443" />

Also, to handle the client's real IP address in logs, add the RemoteIpValve configuration under the Host node in server.xml:

<Host name="localhost" appBase="webapps"
      unpackWARs="true" autoDeploy="true">

    <!-- Remote IP Valve for handling proxy IP addresses -->
    <Valve className="org.apache.catalina.valves.RemoteIpValve"
           internalProxies="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
           remoteIpHeader="x-forwarded-for"
           proxiesHeader="x-forwarded-by"
           protocolHeader="x-forwarded-proto" />

    <!-- Access log configuration -->
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log" suffix=".txt"
           pattern="%h %l %u %t \"%r\" %s %b" />
</Host>

Configure Nginx

Update Nginx configuration to reverse proxy to the new Tomcat connector. Create or modify the site configuration file for tomcat.sampledomain.com:

server {
    listen          80;
    server_name     tomcat.sampledomain.com;
    root            /opt/tomcat/webapps/;
    underscores_in_headers on;

    location / {
        proxy_pass              http://localhost:9090/;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-NginX-Proxy true;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_set_header        Host $http_host;
        proxy_set_header        Upgrade $http_upgrade;
        proxy_redirect          off;
        proxy_http_version      1.1;
        proxy_set_header        Connection "upgrade";
    }
}

Ensure to reload or restart both Tomcat and Nginx services after these changes for them to take effect.

Additional resources

For more details or alternative configurations, consider exploring the following resources:

These resources can provide additional perspectives and solutions that may enhance or troubleshoot your current setup.

Created by Julieth Last modified by Aadrian on Dec 13, 2024