1

I am trying to proxy_pass users with certain IPs to http://server1 and certain other users to http://server2. I'd like to return 403 if the user doesn't match any IP. Here's what I have:

geo $userGroup1 {
        default 0;
        192.168.178.2 1;
}
geo $userGroup2 {
        default 0;
        192.168.178.3 1;
}

server { listen 80 default_server; listen [::]:80 default_server;

    server_tokens off;
    server_name _;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        if ($userGroup1) {
                proxy_pass http://server1 
        }
        if ($userGroup2) {
                proxy_pass http://server2
        }

        # return 403 <-- returns 403 for all users

    }

}

How would my config need to be changed?

2 Answers2

2

Have finally gotten around testing this, do keep in mind that "proxy_pass" cannot contain a URI in example below, use an IP address.

If you want to forwad to another server by URI, you could maybe use "return" or "rewrite" instead of "proxy_pass"; For more information click here.

geo $remote_addr $userGroup {
        default             0;
        192.168.178.2       1;
        192.168.178.3       2;
}

server { listen 80; listen [::]:80;

server_name _;
server_tokens off;

index index.html index.htm index.nginx-debian.html;

location / {
        if ($userGroup = 1) {
                proxy_pass https://192.168.178.201;
        }
        if ($userGroup = 2) {
                proxy_pass https://192.168.178.202;
        }

        return 403; # Anyone else would get a 403
}

}

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. – Community Aug 28 '22 at 16:01
0

Try to use the directive 'break' inside the 'if' statement, like this:

geo $userGroup1 {
       default 0;
       192.168.178.2 1;
}

geo $userGroup2 { default 0; 192.168.178.3 1; }

server { listen 80 default_server; listen [::]:80 default_server;

    server_tokens off;
    server_name _;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        if ($userGroup1) {
                proxy_pass http://server1;
                break; # <-------- HERE
        }
        if ($userGroup2) {
                proxy_pass http://server2;
                break; # <-------- HERE
        }

        return 403; # <-- returns 403 for all users

    }

}

Jose
  • 1