以下是一个配置 Nginx + PHP 支持 HTTP 目录列表的示例:
核心配置说明
- 目录列表:使用 
autoindex on开启目录浏览 - PHP 处理:通过 FastCGI 将 PHP 请求交给 PHP-FPM 处理
 - 安全隔离:禁止显示敏感文件(如 
.env) 
完整 Nginx 配置示例
server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/html;
    index index.php index.html;
    # 主目录配置
    location / {
        autoindex on;                   # 启用目录列表
        autoindex_exact_size off;      # 显示文件大小(KB/MB格式)
        autoindex_localtime on;         # 显示本地时间
        autoindex_format html;          # HTML格式输出
    }
    # PHP 处理配置
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 根据实际版本修改
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
    # 隐藏敏感文件(可选)
    location ~ /\.(env|git) {
        deny all;
        return 403;
    }
}
关键参数说明
| 指令 | 作用 | 
|---|---|
autoindex on | 
启用目录列表 | 
autoindex_exact_size off | 
人性化显示文件大小 | 
autoindex_localtime on | 
显示服务器本地时间 | 
autoindex_format html | 
使用 HTML 格式化输出 | 
效果示例
访问 http://yourdomain.com/some-directory/ 将显示:
📁 Parent Directory/
📁 Subfolder/
📄 image.jpg (1.2 MB)
📄 document.pdf (350 KB)
📄 script.php (可执行)
安全建议
- 仅限内网使用:生产环境不建议开启目录列表
 - 访问限制:添加基础认证
location /protected { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; } - 禁用 PHP 执行(特定目录):
location ^~ /uploads { location ~ \.php$ { deny all; } } 
验证步骤
- 保存配置到 
/etc/nginx/sites-available/default - 测试配置:
sudo nginx -t - 重载服务:
sudo systemctl reload nginx - 创建测试目录:
mkdir -p /var/www/html/{public,uploads} touch /var/www/html/public/{test.php,image.jpg} 
⚠️ 注意:确保 PHP-FPM 服务正常运行,且 sock 文件路径与实际版本匹配(可通过
ls /var/run/php/查看)

Leave a Reply