nginx 重定向不是来自负载平衡的内容

nginx 重定向不是来自负载平衡的内容

我有nginx服务器1充当之间的负载平衡服务器1服务器2

服务器1我将负载平衡的上游定义为:

upstream server
    # SELF SERVER1 [localhost]
    server 127.0.0.1:8082 weight=3 max_fails=3 fail_timeout=2;
    # other SERVER2
    server otherserverip:8082 max_fails=3 fail_timeout=2;
}

负载平衡配置服务器1是这个吗:

server {
    listen   80;
    server_name ~^(de|es|fr)\.server\.com;
    location / {
        proxy_pass   http://server;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

        # trying to pass a variable in the header to SERVER2
        proxy_set_header        Is-From-Load-Balancer 1;        
    }
}

然后在服务器2我有:

server {
    listen   8082;
    server_name localhost;
    root   /var/www/server.com/public;
    # test output values
    add_header testloadbalancer $http_is_from_load_balancer;
    add_header testloadbalancer2 not_load_bal;

    ## other stuff here to process the request
}

我可以看到,当请求来自负载平衡时,响应标头中的“testloadbalancer”设置为 1,而从直接访问时则不存在:服务器2:8082

我想回到服务器1所有直接请求发送到服务器2,但保留来自负载平衡的那些。因此这应该禁止直接访问服务器2:8082并重定向至服务器1:80

答案1

我按照这里关于 nginx 中多个 if 条件的示例找到了一个可行的解决方案 [http://rosslawley.co.uk/2010/01/nginx-how-to-multiple-if-statements/]:

服务器2

server {
  listen   8082;
  server_name localhost;
  root   /var/www/server.com/public;

  set $is_load_balancer FALSE;
  if ( $http_is_from_load_balancer ) {
    set $is_load_balancer TRUE;
  }

  if ( $is_load_balancer = FALSE )  {
    # here you redirect to the server.com 
    # so this will be processed again by the load balancing 
    rewrite ^ http://server.com$request_uri? permanent;  
  }    
}

相关内容