SSL + NGINX + Tomcat

Quick guide to secure Tomcat running behind NGINX as reverse proxy/load balancer

SSL + NGINX + Tomcat
NOTE: Tutorial assumes you are already comfortable with setting Tomcat and NGINX.

NGINX is one of our favourite reverse proxy/load balancer which fits nicely with our servlet container Tomcat. Our organisation takes security very seriously. And here I’ll quickly brief you about how to integrate SSL at NGINX with a tomcat.

Step1: Test App built with Spring framework

You can download the app from my github. This is a simple app having two URLs: See this gist.

1. /

This will create a SESSION COOKIE and return a simple message.

2. /redirect

This will simply redirect to above URL

Its a maven project and if you have build it already and deployed in tomcat. This is what you will see.

Root URL with non secure session cookie

Step 2: Scaling and securing the app for production

In any prod env, your app servers will sit behind a load balancer, NGINX in our case. Assuming you already have NGINX installed and SSL configured in this, configuration would look similar to this snippet.

So now if we access the same URL via NGINX again, this is what it looks like.

URL is secure via https but Session cookie is still not secure

Even though our URL has become secured (https) but notice the secure flag in the session cookie. It is not marked as secure and this is not acceptable when security is our utmost priority.

Why this happened?

When the session cookie is generated, Tomcat will mark the secure flag based on protocol scheme via which this request is coming, in our case its http at port 8080.

STEP 3: Telling Tomcat to respect originating protocol scheme from our NGINX

Simply add below Valve in Engine settings as seen here. Basically this adds an additional processing in Tomcat’s request handling pipeline and updates the protocol scheme based on the originating scheme.

<Valve className=”org.apache.catalina.valves.RemoteIpValve”

NOTE: Replace internalProxies prop above with your nginx ip

NOTE: Tested with Tomcat version 8.0.43

Now if everything went well, this is what you should see if you access your app via NGINX web server. Our protocol scheme is correctly set to https and SESSION cookie is automatically marked as secured.

Fully Secured SSL integration of NGINX with Tomcat
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.