Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have nginx on SERVER1 that is acting as load balancing between SERVER1 and SERVER2

in SERVER1 I have the upstream for the load balancing defined as :

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

The load balancing config on SERVER1 is this one:

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

Then in SERVER2 I have:

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
}

I can see the "testloadbalancer" in the response header is set to 1 when the request is coming from the load balancing, it is not present when from a direct access: SERVER2:8082 .

I would like to bounce back to the SERVER1 all the direct requests that are sent to SERVER2, but keep the ones from the load balancing. So this should forbid direct access to SERVER2:8082 and redirect to SERVER1:80 .

share|improve this question

1 Answer 1

up vote 0 down vote accepted

I managed to find a working solution by following the examples here on multiple if conditions in nginx [ http://rosslawley.co.uk/2010/01/nginx-how-to-multiple-if-statements/ ] :

in SERVER2

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;  
  }    
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.