3

I'm trying to load balance a web application through nginx, It works fine for all will my web application calls a service with sub-path.

for example it works

http://example.com/luna/ 

but not for

 http://example.com/luna/sales

My nginx.conf

user  nobody;
worker_processes  auto;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

     map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }

    upstream lunaups {
        server myhostserver1.com:8080;
        server myhostserver2.com:8080;
    }


    server {
        listen       80;
        server_name  example.com;

        proxy_pass_header Server;

        location = / {
             rewrite ^ http://example.com/luna redirect;
         }

        location /luna {
            rewrite ^$/luna/(.*)/^ /$1 redirect;
            proxy_pass http://lunaups;
            #add_header  X-Upstream  $upstream_addr;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

my web application calls a service with additional subpath like /luna/sales fails to return response. What am i missing here?

It works if i remove one of my host server from upstream, But when I add second host on upstream it fails to return response.

Is my rewrite rule wrong or my configurations as whole is wrong?

1 Answers1

0

Your rewrite rule redirects the web browser from /luna/sales to /sales. This means the web browser does a new HTTP request for /sales, but then you have no location block that matches /sales so you get a 404 error.

I believe what you really are trying to do is changing the URI that is proxied to the upstream. If so, you could try changing your location block:

location ~ /luna(?<upstream_uri>(/.*)?) {
    proxy_pass http://lunaups/$upstream_uri;
}

This will match either /luna or /luna/whatever, bind the matched subexpression as $upstream_uri and then send only that subexpression to your upstream.

Emil Vikström
  • 542
  • 3
  • 11
  • Hi Emil, It won't work. I'm Using Jetty as backend webserver.My web application as whole runs on /luna, but on my webpage(e.g "about" page) a request is triggered(e.g luna/about/) but it wont get any response. On browser my path is still /luna. – Karthick Radhakrishnan Sep 16 '16 at 07:34