nginx location deny by file extension syntax

2019-02-26 06:59发布

I wrote two different settings, one for denying access to dotfiles, and the other for denying access to a list of file extensions.

But, is there any syntax that could deny dotfiles in the list of other file extensions?

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条回答
趁早两清
2楼-- · 2019-02-26 07:21

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

查看更多
登录 后发表回答