在 CentOS 上把 readdir(目录遍历) 和 Nginx 结合起来,通常有三种常见场景,下面按使用频率和实用性给你说明。
如果你的需求只是 “让 Nginx 列出某个目录下的文件”,不需要自己写 readdir 代码,这是最简单的方式。
yum install -y nginx
systemctl enable nginx
systemctl start nginx
编辑 Nginx 配置:
vi /etc/nginx/conf.d/list.conf
示例:
server {
listen 80;
server_name example.com;
location /files/ {
root /data;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
}
目录结构示例:
/data/files/
访问:
http://example.com/files/
✅ 效果:类似 ls 的网页版目录列表
✅ 本质:Nginx 内部调用 readdir()
如果你想 自己用 readdir() 读取目录,再交给 Nginx 展示,一般通过:
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir("/data/files");
struct dirent *entry;
printf("Content-Type: text/html\n\n");
printf("<ul>");
while ((entry = readdir(dir)) != NULL) {
printf("<li>%s</li>", entry->d_name);
}
printf("</ul>");
closedir(dir);
return 0;
}
location /list/ {
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
}
⚠️ 需要:
spawn-fcgifcgi 开发库如果你只是想在 Web 页面中 用 readdir 逻辑,PHP 是最省事的。
<?php
$dir = "/data/files";
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo $file . "<br>";
}
closedir($dh);
}
?>
yum install -y php php-fpm nginx
systemctl start php-fpm nginx
Nginx 配置:
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
| 需求 | 推荐方案 |
|---|---|
| 只浏览目录 | Nginx autoindex |
| 自定义目录展示 | PHP + readdir |
| 高性能 / 自研 | C + FastCGI |
| 文件下载站 | Nginx autoindex + auth |
/ 或 /root 暴露location 限制路径auth_basiclocation /files/ {
autoindex on;
deny 1.2.3.4;
}
如果你能提供:
我可以直接给你一套 可运行的 CentOS + Nginx 配置示例。