使用上游时NGINX没有响应

时间:2016-09-16 06:51:55

标签: nginx http-headers proxypass nginx-location

我试图通过nginx对Web应用程序进行负载均衡,它可以正常运行,我的Web应用程序将调用带有子路径的服务。

例如它起作用

http://example.com/luna/ 

但不适用于

 http://example.com/luna/sales

我的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;
        }
    }
}

我的Web应用程序调用带有其他子路径的服务,例如/ luna / sales无法返回响应。我在这里缺少什么?

如果我从上游删除一个主机服务器,它可以工作但是当我在上游添加第二个主机时,它无法返回响应。

我的重写规则是错误的还是整个配置错了?

1 个答案:

答案 0 :(得分:0)

rewrite指令有四个后缀,它们都有特定的用途。有关详细信息,请参阅this document

如果您希望将URI /映射到/luna而不更改浏览器中的URL,则可以使用rewrite ... last进行内部重写。例如:

location = / {
    rewrite ^ /luna last;
}

location /luna块中,您需要在将URI发送到proxy_pass语句之前重写URI(不离开位置块),这需要rewrite ... break。例如:

location /luna {
    rewrite ^/luna(/.*)$ $1 break;
    rewrite ^ / break;
    proxy_pass http://lunaups;
}

第一次重写会更改任何带有子路径的URI,第二次重写会处理没有子路径的URI。

在正则表达式上查看this useful resource