温馨提示×

centos readdir如何结合nginx

小樊
52
2026-10-26 16:37:07
栏目: 智能运维

在 CentOS 上把 readdir(目录遍历) 和 Nginx 结合起来,通常有三种常见场景,下面按使用频率和实用性给你说明。


一、直接用 Nginx 的 autoindex(最常用,无需编程)

如果你的需求只是 “让 Nginx 列出某个目录下的文件”,不需要自己写 readdir 代码,这是最简单的方式。

1. 安装 Nginx(CentOS)

yum install -y nginx
systemctl enable nginx
systemctl start nginx

2. 配置目录浏览

编辑 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()


二、用 C / C++ readdir + Nginx(FastCGI / CGI)

如果你想 自己用 readdir() 读取目录,再交给 Nginx 展示,一般通过:

  • CGI
  • FastCGI(推荐,如 spawn-fcgi + fcgi)

示例:C 程序使用 readdir

#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;
}

配合 Nginx(FastCGI 示例)

location /list/ {
    fastcgi_pass 127.0.0.1:9000;
    include fastcgi_params;
}

⚠️ 需要:

  • spawn-fcgi
  • fcgi 开发库
  • 编译 C 程序为 FastCGI

三、Nginx + PHP 的 readdir(最常见 Web 方案)

如果你只是想在 Web 页面中 用 readdir 逻辑,PHP 是最省事的。

PHP 示例(readdir)

<?php
$dir = "/data/files";
if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
        echo $file . "<br>";
    }
    closedir($dh);
}
?>

Nginx + PHP-FPM(CentOS)

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_basic
  • ✅ 禁止执行脚本
location /files/ {
    autoindex on;
    deny 1.2.3.4;
}

如果你能提供:

  • 想用 C / PHP / Python?
  • 是 文件浏览 / 接口 / 下载站?

我可以直接给你一套 可运行的 CentOS + Nginx 配置示例。

0 踩