Redirect a subpath to a external host with Nginx

I need to create a quite simple map in Nginx redirecting a subpath to another server that is located in the same subnet.

  • Nginx server: 192.168.0.2
  • Tomcat server: 192.168.0.3:8443

I tried to put this in the server section

    location /tomcatapi/ {
        rewrite /tomcatapi/(.*) $1 break;
        proxy_pass http://192.168.0.3:8443;
    }

but all I get accessing http://www.myservice.com/tomcatapi/ is a 500 error page and in nginx log file I have this error:

    the rewritten URI has a zero length

What I am missing in this conf?


Solution 1:

Let's look at your rewrite line:

rewrite /tomcatapi/(.*) $1 break;

You're taking the bit in brackets (i.e. everything after /tomcatapi/), which gets assigned to $1, and using that as the sole contents of your rewritten URI.

In your example, there is nothing after /tomcatapi/, so the rewrite ends up empty, and this is what nginx is moaning about.

If you change the rewrite rule to

rewrite /tomcatapi/(.*) /$1 break;

then you'll always end up with at least / in the rewrite output.