nginx的autoindex

如果想要把服务器上的某个目录对外开放,让所有人可以看到并下载目录里面的文件,可以使用nginx的autoindex

举个例子,我想把/home/nemo/publicdir/file/这个目录对外开放,我可以设置请求http://wwww.mysite.com/testpublic/这个url的时候,自动映射到我要开放的目录。nginx配置如下:

location /testpublic/ {
	alias /home/nemo/publicdir/file/;
	autoindex on;
}

location / {
	root /home/nemo/www;
	try_files /notfound.html 404;
}

然后重启nginx,之后在浏览器里面输入http://wwww.mysite.com/testpublic/就可以看到/home/nemo/publicdir/file/这个目录里面的文件了。

注意:目录里面有index.html的时候,输入上面的地址,看到的是index.html的东西,所以如果要让其他看看到目录里的东西,则该目录下面不能有index.html文件


我之前的一篇关于nginx location规则的笔记里面写过一些匹配规则,下面看看假如说上面的匹配规则写成如下这几个方式,会怎么样?

方式一、=全匹配

location = /testpublic/ {
	alias /home/nemo/publicdir/file/;
	autoindex on;
}

location / {
	root /home/nemo/www;
	try_files /notfound.html 404;
}

由于=表示全匹配,比如说/home/nemo/publicdir/file/里面还有一个logs文件夹,则在浏览器里面输入http://wwww.mysite.com/testpublic/之后可以看到里面的logs文件夹,但是点击该文件夹,浏览器地址栏里面变成了http://wwww.mysite.com/testpublic/logs,但实际上nginx匹配的是location /规则。

方式二、~匹配子字符串

location ~ /testpublic/ {
	alias /home/nemo/publicdir/file/;
	autoindex on;
}

location / {
	root /home/nemo/www;
	try_files /notfound.html 404;
}

~表示匹配是否是uri的子字符串,还用上面的logs文件夹举例,在浏览器里面输入http://wwww.mysite.com/testpublic/之后可以看到里面的logs文件夹,但是点击该文件夹,浏览器地址栏里面变成了http://wwww.mysite.com/testpublic/logs,但看到的还是/home/nemo/publicdir/file/文件夹的内容,因为/testpublic//testpublic/logs的子字符串,nginx匹配的还是location ~ /testpublic/规则。

可能上面这个例子会让人误以为~是从头开始匹配,实际不是。可以举一个更明显的例子,在浏览器里输入http://wwww.mysite.com/blablabla/testpublic/,结果看到的还是/home/nemo/publicdir/file/文件夹的内容。因为/testpublic//blablabla/testpublic/的子字符串。


看下nginx官方文档的autoindex这一章节,里面还提到autoindex_localtimeautoindex_formatautoindex_exact_size等参数。下面会一一解释。

autoindex_exact_size默认是on,表示显示出文件的确切大小,单位是Byte。如果设置为off,显示的是文件的大概大小,单位是KBMBGB

autoindex_localtime默认是off,表示显示文件的时间为GMT时间,改为on后闲置的文件时间是服务器时间。

下面这张图是autoindex_exact_sizeonautoindex_localtimeoff的文件时间和大小显示情况

autoindex_exact_size_on-loccaltime-off

下面这张图是autoindex_exact_sizeoffautoindex_localtimeon的文件时间和大小显示情况

autoindex_exact_size_off-localtime-on

autoindex_format这个参数从nginx 1.7.9版本才有,默认是html,表示目录里的文件以html的形式形式返回。

Show Comments