NGINX Allow/Deny based on IP & User Agent combination

I have a question regarding the allow/deny rule for NGINX based on User Agent+IP.

I currently have the following in my nginx.conf to permit all Internet connections based on a certain User Agent Value of "iOS".

server { 
    proxy_set_header    Proxy-Connection "";

    listen      *:8443;
    server_name  myserver.com;

    if ($http_user_agent !~* (ELB|ios)) {
        return 403;
    }

    location / {
        proxy_http_version  1.1;
        proxy_pass        https://myserver;
        proxy_set_header Connection "upgrade";
    }
}

I wanted to permit access to the following combination of:

  • Any "IP" + "UserAgent" value of 'iOS'

or

  • IP Subnet 192.168.2.0/24 + "UserAgent" value of 'chrome'

Thanks in advance.


Any "IP" + "UserAgent" value of 'iOS'

So all you need to do is deny by default allow any UserAgent that is iOS.

IP Subnet 192.168.2.0/24 + "UserAgent" value of 'chrome'

What you are trying to do in this case if create a compound if in Nginx.

Jrom on GitHub has created a script to do that.

https://gist.github.com/jrom/1760790

If we create a script using Jrom's as an example use some implement a process posted by kolbyjack, we can make what you are looking for.

set $test  DENIED;

geo $good_user {
  default 0;
  192.168.2.0/24 1;
}

if ($http_user_agent ~* (ELB|ios)) { 
  set $test  ALLOWED; 
} 

if ($good_user) { 
  set $test  DE; 
} 

if ($http_user_agent ~* (chrome)) { 
  set $test  "${test}V"; 
} 

if ($test = ALLOWED) { 
  proxy_pass https://myserver; 
  break; 
} 

if ($test = DEV) { 
  proxy_pass https://myserver; 
  break; 
} 

if ($test = DE) {
return 403;
}

if ($test = V) {
return 403;
}

if ($test = DENIED) {
return 403;
}