nginx:禁止访问文件夹,但某些子文件夹除外

nginx:禁止访问文件夹,但某些子文件夹除外

如何才能拒绝对文件夹的访问,但可以拒绝其中的一些子文件夹的访问?

我尝试了类似的方法(按此顺序):

#此子文件夹不应被拒绝,并且其中的 php 脚本应可执行

位置 ~ /data/public { 允许所有; }

#此文件夹包含许多应禁止公开访问的子文件夹

位置 ~ /data { 全部拒绝;返回 404;}

... 无法正常工作。 /data/public 文件夹中的文件可以访问(/data 中的所有其他文件都被拒绝,这是理所当然的),但 /data/public 文件夹中的 PHP 文件不再执行(如果我不添加这些限制,PHP 文件是可执行的)。

哪里错了?怎么才能正确呢?我觉得有更好的方法。

如果有人能帮助我,那就太好了:)。


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

<? echo "test"; ?>

它为您提供此文件作为下载(没有上面的“拒绝”配置,php 文件运行良好)。

我的PHP配置:

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 文件均在运行......(其他子文件夹也是如此)。

答案1

php 文件未被处理的原因是,当它到达该/data/public/位置时它会停在那里并且不知道如何处理 php 文件。

尝试将你的 php 位置放在另一个名为 php.conf 的文件中,并将该文件包含在你的服务器块和/data/public/块中。因此你的配置将类似于

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;
}

答案2

位置规则应该是这样的。

location ^~ /data/                { deny all; }

或者

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

nginx location 规则如下

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."

所以工作配置应该是这样的

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

通过使用全部拒绝,它应该返回 403 Forbidden 而不是 404。

这应该允许访问和处理公共目录,并阻止其他任何内容。我在为 Magento 处理 nginx 配置时也遇到了同样的问题,但我通过 ^~ 技巧解决了这个问题。

相关内容