Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 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/;
    # 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
up vote 0 down vote accepted

I managed to find a working solution by following the examples here on multiple if conditions in nginx [ ] :


server {
  listen   8082;
  server_name localhost;
  root   /var/www/;

  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 
    # so this will be processed again by the load balancing 
    rewrite ^$request_uri? permanent;  
share|improve this answer

Your Answer


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.