Ommadawn
Ommadawn

Reputation: 2730

Nginx + Tomcat working in the same server

I'm developing a WebApp using Tomcat. I've set a frontal NGINX server to serve static content and redirect the rest of work to a Tomcat server.

I've set that configuration in NGINX:

proxy_cache_path  /var/www/mysite/assets levels=1:2 keys_zone=my_cache:10m inactive=60m;
proxy_cache_key   "$scheme$request_method$host$request_uri";

server {
        server_name             mysite.com www.mysite.com;
        listen                  443 ssl http2;

        ssl_certificate         /etc/ssl/mysite.crt;
        ssl_certificate_key     /etc/ssl/mysite.key;
        ssl_session_cache       shared:SSL:10m;
        ssl_session_timeout     10m;

        root                    /opt/tomcat/latest/webapps/mysite/;
        index                   index.jsp;

        location ~* \.(jpg|jpeg|png|gif|ico|css|js|xml|gz)$ {
                expires 12h;
        }

        location / {
                proxy_pass              http://127.0.0.1:8080/mysite/;
                proxy_redirect          off;
                proxy_set_header        Host $host;
                proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header        X-Real-IP $remote_addr;
                proxy_set_header        X-Forwarded-Proto $scheme;
                proxy_set_header        X-Server-Proto $server_protocol;

                proxy_cache             my_cache;
                add_header              X-Proxy-Cache $upstream_cache_status;
        }
}

As you can see, I set the proxy redirect and the proxy cache. Using the last directive (add_header X-Proxy-Cache $upstream_cache_status;) I could see if a hva e HIT or a MISS loading resources.

The problems I found are:

  1. If I use this configuration, I think can't see the HIT/MISS headers, so I don't know if it's working well the proxy cache.
  2. If I comment the entire location ~* \.(jpg|jpeg|png|gif|ico|css|js|xml|gz)$ section, I can see the HIT/MISS headers, so I think the proxy cache works, but I don't know if I'm letting Tomcat manage static content, and that is what I wanted to avoid using this section

How could I set the config file to use a proxy cache and let NGINX manage the static content (jpg,css,js,...)? Maybe everything is alright and I've got it well... Which is the best solution?

Thanks.

Upvotes: 0

Views: 1970

Answers (1)

Stefan
Stefan

Reputation: 26

Having add_header X-Proxy-Cache $upstream_cache_status; in the NGINX config means that NGINX looks at expires set on those assets coming from Tomcat and caches them appropriately.

The additional location block

location ~* \.(jpg|jpeg|png|gif|ico|css|js|xml|gz)$ {
                expires 12h;
}

combined with

root                    /opt/tomcat/latest/webapps/mysite/;

will server them from disk and not the proxy, eliminating the need for hitting the proxy cache.

Upvotes: 1

Related Questions