Nginx Ip Whitelist

2019-01-22 18:06发布

I want to configure my nginx proxy server to only allow certain IPs to access it.

To my knowledge, this is normally done in the config file, with allow and deny lists, but I need a different option if possible, since my whitelist is very big. I also need to link this to a website, so that when a user is logged in, the user will be able to update the user's IP if it has changed.

In short, a whitelisted user will be able to use my proxy server, but if for any reason the user's IP changes, the user can still login to my site and update that whitelisted IP.

Where I Need Help

Is there a way for nginx to read an IP whitelist from an external source, from something like htaccess or mysql? If so, what would be the best format for that list, so that it can be easily linked to and automatically updated? I'm planning to get the site professionally built so that when users log in to their accounts, the whitelist is automatically updated. I would therefore like my whitelist to be in the optimal format for the designer to work with, to make it easier to integrate the whitelist with the user accounts.

标签: nginx
2条回答
贼婆χ
2楼-- · 2019-01-22 18:37

There are two ways I know you could solve this problem.

  1. Allow-list in separated config: Works on all common NginX installs

    You can place all of the allow statements in a simple text file, per site, that contains nothing but allow statements. Include that under the client's server block. Use scripts as needed to alter the list. Finally reload (not restart) the nginx config every time you update the allow list. This might look as follows:

    cat /var/www-allow/client1-allow.conf
    allow 192.168.1.1;
    allow 10.0.0.1;
    
    cat /etc/nginx/sites/client1.conf
    ...
    server {
        include /var/www-allow/client1-allow.conf;
        deny all;
    }
    
    echo Test NginX configuration
    nginx -t
    
    echo Reload NginX configuration (**adjust for your setup**)
    service nginx reload
    
  2. Use embedded Lua: Required custom compile of NginX

    Recompile NginX from source with the 3rd party embedded Lua add on module. Use a lua script to actively deny unsupported IP addresses. See the second example under access_by_lua. There are a variety of ways you could use the add on. I suggest using access_by_lua_file to put the lua script in an external location.

Both of these approaches will still require some effort on your part. I don't believe a drop-in solution is already available for your specific objectives.

查看更多
该账号已被封号
3楼-- · 2019-01-22 19:00

Maybe nginx.shared.dict (http://wiki.nginx.org/HttpLuaModule#lua_shared_dict) would help you?

查看更多
登录 后发表回答