Search code examples
nginxwhitelist

Allow any IPs to private_url but only allow whitelisted IPs to public_url in nginx


I have a Java Spring app on WebSphere behind nginx. I have
my_website.com/private_url
my_website.com/public_url
Currently both addresses are accessible from any IP. What is the correct way to tell nginx to only accept requests to my_website.com/private_url from list of whitelisted subnets?


Solution

  • To deny access to everybody except certain addresses to a specific directory or request add this location block

    location ^~ /private_url {
      allow x.x.x.x/32;
      allow x.y.x.x/16; 
      deny all;
    }
    

    The rules are checked in sequence from top to bottom until the first match is found.

    You should add this in nginx.conf, but you don't want editing this file every time you want to add new ip. So instead write all ip addresses in a whitelist.conf in nginx home directory and include this file in location block.

    whitelist.conf

    allow x.x.x.x/32;
    allow x.y.x.x/16;
    

    nginx.conf

    location ^~ /private_url {
      include whitelist.conf; 
      deny all;
    }