nginx位置拒绝文件扩展名语法

时间:2015-10-06 02:52:46

标签: linux security nginx

我写了两个不同的设置,一个用于拒绝访问dotfiles,另一个用于拒绝访问文件扩展名列表。

但是,是否有任何语法可以拒绝其他文件扩展名列表中的dotfiles?

location ~* \.(7z|bak|bash|bz2|config|dist|engine|fla|git|gz|inc|inc|info|ini|install|iso|log|make|module|profile|psd|py|rar|rb|sh|sql|swp|tar|zip)$ {
deny all;
}

location ~ /\. { deny all; access_log off; log_not_found off; }

1 个答案:

答案 0 :(得分:1)

The nginx server uses straight pcre as the library for regular expressions; whatever pcre accepts, so should nginx.

Some testing on OpenBSD with egrep(1) reveals:

$ printf '/t.bak\n/t.bakk\n/t.zipp\n/a.zip\n/.ht\n/t.ht\n' |grep -E '\.(bak|zip)$|/\.' /t.bak /a.zip /.ht $

But OpenBSD's egrep doesn't actually use pcre, but regcomp(3) instead! However, pcre does come with pcregrep, which does produce identical results:

$ printf '/t.bak\n/t.bakk\n/t.zipp\n/a.zip\n/.ht\n/t.ht\n' |pcregrep '\.(bak|zip)$|/\.' /t.bak /a.zip /.ht $

You could also try pcretest for testing the regular expressions (apparently, you must quote them with something like # there):

$ pcretest
PCRE version 8.30 2012-02-04

  re> #\.(bak|zip)$|/\.#
data> /t.bak
 0: .bak
 1: bak
data> /t.baki
No match
data> /.h
 0: /.
data> ^D
$

I.e., to summarise: just concatenating the two expressions with | should work.

location ~* \.(bak|zip)$|/\. {
    deny all;
}

However, for the sake of maintenance (and since you've had to ask this question in the first place), you might as well want to keep these expressions apart for a clearer overview of what the config is all about. (The two expressions apart might even be more efficient due to some kind of end-of-line optimisation than when merged together, but that's just a wild guess on my part.)