当子目录名称未知时,Nginx 阻止访问子目录

Nginx block access to sub directory when sub directory name is unknown

我正在尝试设置 Nginx 为用户显示 public 文件夹中的文件。该站点将有多个用户,每个用户都有一个 Nginx 未知名称的子目录。

示例目录结构:

/users/usernameHere/public
/users/usernameHere/private

我只希望 nginx 显示用户 public 目录中的文件并拒绝对任何其他目录的所有访问。

这是我到目前为止尝试过的:

location ^~ /users/*/public/ {
    allow all;
    try_files $uri $uri/ =404;
}

location ^~ /users/ {
    deny all;
}

试试这个配置

location ~ /users/.*/public/ {
    allow all;
    try_files $uri $uri/ =404;
}

location /users/ {
    deny all;
}

阅读 official docs 以查看 uri 之前的修饰符之间的区别,您的第一个位置是正则表达式位置,应使用 ~*~ 区分大小写和大小写-不敏感的匹配项。

A location can either be defined by a prefix string, or by a regular expression. Regular expressions are specified with the preceding “~*” modifier (for case-insensitive matching), or the “~” modifier (for case-sensitive matching).

那么你的第二个位置就是一个由前缀字符串/users/定义的普通位置,你使用的修饰符^~意味着跳过正则表达式检查并使用当前最长的匹配前缀,这里是/users/ 一个,因此根据您的配置,您将始终获得 403 return。

If the longest matching prefix location has the “^~” modifier then regular expressions are not checked.