Nginx rewrite .jsp extension and proxy to tomcat

nginxPROXYrewritetomcat

Incoming request

How can i create a Nginx rewrite rule in the appriopriate server block, that takes any URL, that does not end on .do and add an .jsp extension, and than hand over the request to the proxied (Tomcat) server?

Outgoing request

How can i create a Nginx rewrite rule in the apprioate server block, that takes any URL received from the proxied (Tomcat) server that ends on .jsp, remove the .jsp extension, and send the response to the client?

Test

I tried to play around with the following

server {
        listen 443 ssl;
        server_name www.test.local test.local;

        location / {
                if ($request_uri ~ ^/(.*)\.jsp$) {
                        return 302 /$1;
                }
                try_files $uri.jsp @proxy;
        }

        location @proxy {
                proxy_pass http://websites/;
                include proxy_params;
        }
}

Nginx removes the .jsp extension when the request is received, but Nginx also sends the request to Tomcat without the .jsp extension, so tomcat does not know what to look for and returns a 404.

I have confirmed the above by looking at both Nginx and Tomcat server
logs.

The problem

As far as i can tell, Nginx is not asking Tomcat do you have a $uri.jsp page but is instead asking if tomcat has a $uri page (without .jsp extension).

As far as i can read and understand, the try_files syntax is

try_files [Location[file, folder]] [fallback[file, folder, HTTP code]]

But the official documentation does not say (as far as i can find) how to instruct Nginx to (in this case) ask the proxy for the different files and folders to try, but is instead quering its own local root location for $uri.jsp and than using @proxy as fallback.

Best Answer

I think I know what you need:

location ^~ .jsp {
  rewrite /(.*).jsp /$1  break;
  proxy_pass         http://websites;
  proxy_redirect     off;
  proxy_set_header   Host $host;
}

Instead of return 302, you better off rewriting the request applying the transformation you need without the redirection.

This way you have one less roundtrip from browser to server and back again.