Home > Net >  When using Nginx reverse proxy, how can I set IP whitelist based on request URI parameter?
When using Nginx reverse proxy, how can I set IP whitelist based on request URI parameter?

Time:03-16

My url like this:

http://myserver/app/inf?ConId=Obj:com.aaa.bbb:3712 # Only IP in whitelist can access
http://myserver/app/...... # all user can access

When the parameter of ConId is Obj:com.aaa.bbb:3712, I need to restrict only specific IP can access my server.

I tried the following Nginx configuration but not working.

 location / {
            if ( $arg_ContainerOid = "Obj:com.aaa.bbb:3712" ) { 
                allow 192.168.1.104;
                deny  all;
            }
            proxy_pass http://192.168.234.130:80;
            add_header Access-Control-Allow-Origin *;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_http_version 1.1;
            allow all;
        }

Please help, thanks!

CodePudding user response:

You can use something like this:

location / {
  auth_request /auth-here; 
}

location /auth-here {
  internal;
  proxy_pass http://192.168.234.130:80/auth.php;
  proxy_pass_request_body off;
  proxy_set_header Content-Length "";
  proxy_set_header X-Original-URI $request_uri;
} 

Then in your script you can check $_SERVER['HTTP_X_ORIGINAL_URI'] and return HTTP 200 to allow the request or HTTP 403 to deny the request.

You will need the http_auth_request_module for the above to work, as explained in the documentation.

CodePudding user response:

Could use something like:

if ($arg_ConId = "Obj:com.aaa.bbb:3712") {
   set $BLOCKING A;
}
if ($remote_addr != 192.168.1.104) {
   set $BLOCKING "${BLOCKING}B";
}
if ($BLOCKING = AB) {
   return 403;
   break;
}

in server block.

Problems in your code:

  • if Directives in location are considered as evil due to nginx` strange declaration rules. They're doing most of the time strange things, so try to avoid it.
  • $arg_ContainerOID does not catch an argument named "ConId"

Remark: This is not working in dockerized nginx in bridge mode, because the real IP is masked by the firewall.

  • Related