Nginx Custom Autoindex Page


To serve a custom autoindex page for every directory without an index file, just add your autoindex file as an index file. But you have to set it with an absolute path (which is relative to the server root), otherwise it would look only in the requested directory.

It does not matter if you set autoindex on/off

Nginx site config file (/etc/nginx/sites-enabled/myDomain)
server {
  ...
  root /var/www/mydomain;
  index index.php index.html /autoindex.php;

  autoindex off; #Unnecessary
}


PHP autoindex table generation example
<table id=table><thead><tr>
<th onclick=sortTable(0)>Filename</th><th onclick=sortTableBySize(1)>Size</th><th onclick=sortTable(2)>Mod Time</th></tr>
</thead><tbody>
<?php
$units = [' B',' KB',' MB',' GB',' TB',' PB'];
$autodir = '.'.str_replace(array('\\','"',';','$','.'),'',$_SERVER['REQUEST_URI']);

function GetDirSize($path) {
  $bytes = 0;
  if(file_exists($path))
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $ob)
      if($ob->isFile())
        $bytes += $ob->getSize();
  return $bytes;
}

function humanBytes($bytes) {
    for ($i = 0; $bytes > 1024; $i++) $bytes /= 1024;
    return round($bytes, 2) . $GLOBALS['units'][$i];
}
if($dir = opendir($autodir)) {
  while($files[] = readdir($dir)) continue;
  closedir($dir);
  unset($files[array_search('.',$files,true)]);
  unset($files[array_search('..',$files,true)]);
  unset($files[array_search(false,$files,true)]);

  sort($files,SORT_STRING | SORT_FLAG_CASE);

  foreach($files as $file) {
    if(is_dir($autodir.$file)) {
      $fsize = GetDirSize($autodir.$file);
      echo '<tr dir><td><a href="'.$file.'">'.$file.'</a></td><td fsize=',$fsize,'>'.humanBytes($fsize).'</td><td>'.date('Y-m-d H:i',filemtime($autodir.$file)).'</td></tr>';
    }
  }
  foreach($files as $file) {
    if(is_file($autodir.$file)) {
      $fsize = filesize($autodir.$file);
      echo '<tr><td><a href="'.$file.'">',$file,'</a></td><td fsize=',$fsize,'>',humanBytes($fsize),'</td><td>',date('Y-m-d H:i',filemtime($autodir.$file)),'</td></tr>';
    }
  }
}
?>
</tbody></table>