Nginx IP白名单

32

我想配置我的nginx代理服务器,只允许特定的IP地址访问。

据我所知,通常是在配置文件中使用allow和deny列表进行操作,但如果可能的话,我需要一种不同的选项,因为我的白名单很大。我还需要将其与网站链接起来,这样当用户登录时,用户将能够更新其IP地址(如果已更改)。

简而言之,被列入白名单的用户将能够使用我的代理服务器,但如果出于任何原因,用户的IP地址发生了变化,用户仍然可以登录到我的网站并更新白名单中的IP地址。

我需要帮助的地方

是否有一种方法使nginx从外部源读取IP白名单,例如htaccess或mysql?如果有,最好使用什么格式来编写该列表,以便可以轻松地链接并自动更新?我计划让专业人士构建该网站,以便用户登录其帐户时自动更新白名单。因此,我希望我的白名单采用最佳格式,以便设计师更容易地集成白名单与用户帐户。

2个回答

44
我知道两种方法可以解决这个问题。
  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.

这两种方法仍然需要你付出一些努力。我认为没有现成的解决方案适用于你具体的目标。


client1-allow.conf可能是最好的路线,因为您可以即时更新它。我不知道服务是否需要重启才能获取任何更改? - ProfessionalAmateur
4
NginX服务不必重新启动,但必须通过命令行或适当的脚本指示其实时重新加载配置。我使用“service nginx reload”命令,通过“kill -HUP $pidfile”发送HUP信号给nginx。 - Kevin A. Naudé
1
如果在 Docker 中,您可以使用 docker exec <docker-name> nginx -s reload - YoniXw

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接