12

Is it possible to have the directory listing in apache return json instead of html?

I'm completely unexperienced with Apache, but I've browsed the documentation for IndexOptions and mod_autoindex. It seems like there's no built in way to configure the output.

Rjoss
  • 123
  • 1
  • 5
  • Have you looked at [mod_dir](http://httpd.apache.org/docs/2.2/mod/mod_dir.html)? – Elliott Frisch Dec 08 '13 at 00:17
  • Good catch - that's exactly what I needed to use. – Rjoss Dec 08 '13 at 22:54
  • I wrote and Apache module that does just that [https://github.com/teknopaul/mod_upload](https://github.com/teknopaul/mod_upload) Project has two modules mod_jsonindex.so is the one you want FYI nginx has json indexing built in. – teknopaul Nov 25 '16 at 15:26
  • slightly unrelated, but `caddy` does it ootb if the request comes with the header `Accept: application/json` – ccpizza Mar 07 '22 at 00:24

2 Answers2

14

I looked at the code in apache source in modules/generators/mod_autoindex.c and the HTML generation is static. You could rewrite this to output JSON, simply search for all the ap_rputs and ap_rvputs function calls and replace the HTML with the appropriate JSON. That's seems like a lot of work though.

I think I would do this instead...

In the Apache configuration for this site, change to...

DirectoryIndex ls_json.php index.php index.html

And then place ls_json.php script into the any directory for which you want a JSON encoded listing:

// grab the files
$files = scandir(dirname(__FILE__));

// remove "." and ".." (and anything else you might not want)
$output = [];
foreach ($files as $file)
  if (!in_array($file, [".", ".."]))
    $output[] = $file;

// out we go
header("Content-type: application/json");
echo json_encode($output);
Andy Jones
  • 6,205
  • 4
  • 31
  • 47
1

You could use mod_dir as follows - create a php script and list your directories how you want (set content-type as appropriate).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249