nginx:禁止访问文件夹,除了一些子文件夹

如何可以拒绝对一个文件夹的访问,但除了其中的一些子文件夹“拒绝”?

我尝试了这样的(按此顺序):

#这个子文件夹不应该被拒绝,PHP脚本里面应该是可执行的

位置〜/ data / public {allow all; }

#这个文件夹包含许多应该被拒绝公开访问的子文件夹

位置〜/数据{全部否认; 返回404; }

…哪个不能正常工作 / data / public文件夹中的文件是可访问的(其他所有in / data被拒绝,因为它应该是这样),但PHP文件不再执行在/ data / public文件夹中(如果我不添加这些限制,PHP文件是可执行的)。

哪里不对? 怎么可能是正确的? 我认为这是一个更好的方法来做到这一点。

这将是非常好的,如果有人可以帮助我这个:)。


谢谢,但PHP文件仍然没有在/ data / public /文件夹中执行,就像一个简单的

<? echo "test"; ?> 

它给你这个文件作为下载(没有上面的“拒绝”configuration,PHP文件运行良好)。

我的PHPconfiguration:

 location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; fastcgi_index index.php; include fastcgi_params; } 

/ data /之外的所有其他目录中的PHP文件正在工作…(其他子文件夹也是如此)。

PHP文件没有被处理的原因是,当它打到/data/public/位置它停在那里,不知道如何处理PHP文件。

尝试把你的php位置放在另一个名为php.conf的文件中,并将该文件包含在服务器块和/data/public/块中。 所以你的configuration看起来像

 server { location ^~ /data/public/ { allow all; try_files $uri $uri/ /index.php?args; # include to avoid writing it twice.. include php.conf } location ^~ /data/ { deny all; } # ..... # Some other config blocks # ..... # Put this line instead of the php config block to avoid writing the php part twice include php.conf } 

php.conf文件将看起来(你的情况)是这样的:

 location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; fastcgi_index index.php; include fastcgi_params; } 

位置规则应该像这样。

 location ^~ /data/ { deny all; } 

要么

 location ^~ /data/public/ { allow all; } 

nginx的位置规则如下

 To find a location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the most specific one is searched. Then regular expressions are checked, in the order of their appearance in a configuration file. A search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then a configuration of the most specific prefix location is used. 

nginx的访问规则如下

 "Access rules are checked according to the order of their declaration. The first rule that matches a particular address or set of addresses is the one that is obeyed." 

所以一个工作的configuration应该看起来像

 location ^~ /data/public/ { allow all; } location ^~ /data/ { deny all; } 

通过使用拒绝所有,它应该返回403禁止而不是404。

这应该允许访问和处理公共目录,并阻止其他任何东西。 当我正在为Magentoconfigurationnginxconfiguration时,我遇到了同样的问题,但是我通过^〜技巧来解决这个问题。