我需要限制对目录“testdir”中任何文件或子目录的访问。我的配置:
...
location ~* ^.+\.(jpg|txt)$ {
root /var/www/site;
}
location /testdir {
deny all;
return 404;
}
...
Run Code Online (Sandbox Code Playgroud)
在我的配置中,我对 /testdir/jpg_or_txt-files 没有任何限制。怎么做?
小智 50
在一个位置条目中限制对 nginx 中多个目录的访问
...
location ~ /(dir1|dir2|dir3) {
deny all;
return 404;
}
...
Run Code Online (Sandbox Code Playgroud)
Gui*_*ion 24
这是因为“root”指令在匹配“deny”指令之前匹配。颠倒指令的顺序,它应该可以工作:
...
location /testdir {
deny all;
return 404;
}
location ~* ^.+\.(jpg|txt)$ {
root /var/www/site;
}
...
Run Code Online (Sandbox Code Playgroud)
小智 18
要确保选择 testdir 匹配而不是 jpg/txt 匹配,请使用以下位置:
location ^~ /testdir {
deny all;
return 404;
}
location ~* ^.+\.(jpg|txt)$ {
root /var/www/site;
}
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您有两种类型的位置。location /testdir是一个前缀位置,因为它~在location和之间没有波浪号 ( ) /testdir。
location ~* ^.+\.(jpg|txt)$是一个正则表达式位置(不区分大小写,因为*在波浪号之后)。从nginx 文档:
为了找到与给定请求匹配的位置,nginx 首先检查使用前缀字符串(前缀位置)定义的位置。其中,选择并记住匹配前缀最长的位置。然后按照它们在配置文件中出现的顺序检查正则表达式。正则表达式的搜索在第一次匹配时终止,并使用相应的配置。如果找不到与正则表达式的匹配项,则使用之前记住的前缀位置的配置。
这里的问题是您的 testdir 位置被记住,但随后在正则表达式阶段选择了 jpg/txt 位置,因为它匹配。文档中的以下注释是我基于我的解决方案(上面给出)的内容:
如果最长匹配前缀位置具有“^~”修饰符,则不检查正则表达式。
Rem*_*yNL 12
location /foo {
deny all;
return 404;
}
Run Code Online (Sandbox Code Playgroud)
由于拒绝所有,这将始终为您提供 403...当您希望服务器为您提供 404 时,只需返回 404...就像这样:
location /foo {
return 404;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113036 次 |
| 最近记录: |