如何限制对目录和子目录的访问

我需要限制访问direstory“testdir”中的任何文件或子目录。 我的conf:

... location ~* ^.+\.(jpg|txt)$ { root /var/www/site; } location /testdir { deny all; return 404; } ... 

在我的configuration中,我对/ testdir / jpg_or_txt文件没有限制。 怎么做?

    在一个位置条目中限制对nginx中多个目录的访问

     ... location ~ /(dir1|dir2|dir3) { deny all; return 404; } ... 

    这是因为在“deny”指令可以匹配之前,“root”指令匹配。 颠倒你的指令的顺序,它应该工作:

     ... location /testdir { deny all; return 404; } location ~* ^.+\.(jpg|txt)$ { root /var/www/site; } ... 

    要确保selecttestdir匹配而不是jpg / txt匹配,请使用以下位置:

     location ^~ /testdir { deny all; return 404; } location ~* ^.+\.(jpg|txt)$ { root /var/www/site; } 

    在你的例子中,你有两种types的位置。 location /testdir是一个前缀位置,因为它在location/testdir之间没有代字符( ~ )。

    location ~* ^.+\.(jpg|txt)$是一个正则expression式位置(不区分大小写),因为在代字符后直接是* 。 从nginx文档 :

    要查找匹配给定请求的位置,nginx首先检查使用前缀string(前缀位置)定义的位置。 其中,匹配前缀最长的位置被选中并记住。 然后按照它们在configuration文件中出现的顺序检查正则expression式。 正则expression式的search在第一次匹配时终止,并使用相应的configuration。 如果找不到正则expression式的匹配,则使用先前记住的前缀位置的configuration。

    这里的问题是你的testdir位置正在被记住,但是在正则expression式阶段select了jpg / txt位置,因为它匹配。 下面的文档说明是基于我的解决scheme(上面给出):

    如果最长匹配的前缀位置具有“^〜”修饰符,则不检查正则expression式。

     location /foo { deny all; return 404; } 

    这会一直给你一个403因为所有的拒绝…当你想让服务器给你一个404只是返回一个404 …就像这样:

     location /foo { return 404; }