Nginx动态拒绝/允许IP访问文件


Nginx deny/allow IP access to file dynamically - on the fly

我有一个目录(/var/www/private/)。在这个目录中有三个文件(1.txt,2.txt,3.txt)

我想拒绝每个人访问整个目录和三个文件,但有时我想授予访问该目录中特定IP和特定文件的权限。

在一个名为"block.conf"的文件中,我会列出被授予访问权限的文件和IP地址。我需要nginx读取该文件并相应地拒绝/允许访问(无需每次更改文件时重新加载nginx)。

例如block.conf中的

#denies access to all files in private directory
location /private { 
   deny all;
}
#allows below IP access to 2.txt
location /private/2.txt {
   allow 5.3.7.0;
}
#allows below IP addresses access to 1.txt
location /private/1.txt {
   allow 3.5.7.2;
   allow 9.7.2.2
}

block.conf文件中的位置和IP地址将经常使用PHP进行编辑,我希望nginx相应地拒绝/允许访问该文件。

我认为这将很容易实现,但也存在一些问题:

  • nginx在启动时只读取block.conf一次,不允许我动态修改访问(无需重新加载nginx)
  • location指令不能在block.conf文件中,而不是允许我设置对特定文件的访问权限

如果这在nginx的访问模式下是不可能的,那么我该怎么做呢?如果nginx做不到,还有其他软件可以做到吗?

我能想到的唯一方法是创建一个nginx配置片段,更新它,并让一个以root身份运行的cron脚本偶尔会轮询这个片段,并在它更改时重新加载nginx。

与Apache不同,nginx配置并不是在每次请求时都重新构建的。