Nginx 静态下载站点
示例配置:
static.conf
server {
listen 80;
server_name www.example.com;
charset utf-8;
location / {
root /home/www; # 指定根目录
index NON_EXISTENT_FILE; # 指定index是一个不存在的文件,这样就可以通过ngx_http_autoindex_module模块处理
autoindex on; # 启用目录列表输出
}
access_log /var/log/nginx/static_access.log main;
error_log /var/log/nginx/static_error.log;
}公开静态站点,站点根目录就是 /home/www 中的文件
问题记录
1.不指定 index,会默认查找指定目录的 index.html 文件,报错 404
error.log
2025/04/14 16:12:06 [error] 24296#24296: *1357893 "/tmp/www/index.html" is not found (2: No such file or directory), client: 192.168.50.48, server: www.example.com, request: "GET / HTTP/1.1", host: "192.168.1.236:8888"access.log
ad7b38b9ea507a3443fa330dd2d47faf | - | 192.168.50.48 | - | 14/Apr/2025:16:12:06 +0800 | GET / HTTP/1.1 | 404 | 552 | - | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 | - | 0.000 | - | - | - | 192.168.1.236:8888 | -随便指定一个 index 就可以,可以是index NON_EXISTENT_FILE; 也可以是 index _;
ce16021cb3e172ae1f5315d74afc5afc | - | 192.168.50.48 | - | 14/Apr/2025:16:13:45 +0800 | GET / HTTP/1.1 | 200 | 122 | - | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 | - | 0.000 | - | - | - | 192.168.1.236:8888 | -后续无法复现未指定index,默认访问index.html,这个404问题
2.禁止/开启 输出目录列表
禁止输出目录列表
autoindex 默认值是 off
autoindex off;直接访问根,查看目录,访问提示 403 Forbidden
==> /var/log/nginx/static_error.log <==
2025/04/14 16:18:01 [error] 28518#28518: *1358210 directory index of "/tmp/www/" is forbidden, client: 192.168.50.48, server: www.example.com, request: "GET / HTTP/1.1", host: "192.168.1.236:8888"
==> /var/log/nginx/static_access.log <==
6e8703433855c0edda8c0c43675214d5 | - | 192.168.50.48 | - | 14/Apr/2025:16:18:01 +0800 | GET / HTTP/1.1 | 403 | 552 | - | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 | - | 0.000 | - | - | - | 192.168.1.236:8888 | -直接访问具体的资源,是正常的
http://192.168.1.236:8888/text.txt
$ echo 0 > /tmp/www/text.txt
$ ls /tmp/www/
text.txt显示目录列表
autoindex on;访问根或者子目录,会展示文件列表
$ curl http://192.168.1.236:8888/
<html>
<head><title>Index of /</title></head>
<body>
<h1>Index of /</h1><hr><pre><a href="../">../</a>
<a href="text.txt">text.txt</a> 14-Apr-2025 08:20 2
</pre><hr></body>
</html>一般公共资源,防止别人遍历文件,可以关闭autoindex。这样只能通过具体的文件资源路径访问,无法查看文件目录列表。
站点内部访问,可以开启autoindex,这样便于查找,获取文件