$title

How can I create a simple index.html file which lists all files/directories?

Specifically in apache read more here: Edit the httpd.conf: http://justlinux.com/forum/showthread.php?s=&postid=502789#post502789 (updated link: https://forums.justlinux.com/showthread.php?94230-Make-apache-list-directory-contents&highlight=502789)

or add the autoindex mod: http://httpd.apache.org/docs/current/mod/mod_autoindex.html

There are enough valid reasons to explicitly disable automatic directory indexes in apache or other web servers. Or, for example, you might want to only include certain file types in the index. In such cases you might still want to have a statically generated index.html file for specific folders.

tree

tree is a minimalistic utility that is available on most unix-like systems (ubuntu/debian: sudo apt install tree , mac: brew install tree , windows: zip). tree can generate plain text, XML, JSON or HTML output.

Generate an HTML directory index one level deep:

tree -H '.' -L 1 --noreport --charset utf-8 -o index.html 

Only include specific file types that match a glob pattern, e.g. *.zip files:

tree -H '.' -L 1 --noreport --charset utf-8 -P "*.zip" -o index.html 

The argument to -H is what will be used as a base href, so you can pass either a relative path such as . or an absolute path from the web root, such as /files . -L 1 limits the listing to the current directory only.

tree does not expose a flag to disable the credits in the HTML footer, but you can cut out that block by piping through sed :

# delete 7 lines starting with the line matching 
tree -H '.' -L 1 --noreport --charset utf-8 | sed -e '/
/,+7d' > index.html

For all supported options see tree —help or man tree in a shell.

Generator script with recursive traversal

I needed an index generator which I could style the way I want, and which would also include the file sizes, so ended up writing this script (python 3) which in addition to having customisable styling can also recursively generate an index.html file in all the nested subdirectories (with the —recursive or -r flag). The styling borrows heavily from caddyserver’s file-server module. It includes last modified time and is responsive in mobile viewports.

For me PHP is the easiest way to do it:

Place this in your directory and set where you want it to search on the $path. The first if statement will hide your php file and .htaccess and the error log. It will then display the output with a link. This is very simple code and easy to edit.

Источник

Использование DirectoryIndex в .htaccess

Использование DirectoryIndex в .htaccess

Все Вы знаете, что страница «index.php» открывается по умолчанию. То есть когда Вы указываете в URL путь к каталогу, например так: «http://site.ru/mydir/«, то сервером возвращается файл «index.php» из этого каталога. Если этого файла нет, то возвращается «index.html» или «index.htm«. Если и их нет, то выводится либо содержимое каталога, либо ошибка 403Forbidden«), в зависимости от настроек сервера. Но иногда требуется переопределить страницу по умолчанию и возвращать из каталога совсем другой файл. Именно для такой цели и используется DirectoryIndex в .htaccess.

Давайте приведу пример использования DirectoryIndex в .htaccess:

DirectoryIndex index.html index.htm index.php

Таким образом, будет происходить следующее: при обращении к каталогу будет возвращён файл index.html, если его нет, то index.htm, а если и его нет, то index.php. То есть мы не просто определили те файлы, которые должны открываться по умолчанию, но и их приоритет.

Так же Вы можете и так использовать DirectoryIndex в .htaccess:

Тогда ни один из файлов «index» открываться по умолчанию не будет, а отдаваться сервером будет файл «mainpage.html«. В общем, как видите, «DirectoryIndex» — очень интересная директива, которую иногда можно красиво использовать, хотя, безусловно, требуется это достаточно редко.

Создано 29.01.2011 14:01:20

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 5 ):

    Здравствуйте Михаил! Я сегодня задавал вам вопрос как соеденить HTML с PHP! Вот я сделал так! Я на сервер DENWER в папку WWW которая находится в папке home кинул файлы HTML, CSS и JavaScript! Также папку image в которой находятся картинки! в HTML в теге HEAD я написал КОД, чтобы соеденить CSS и JavaScript! А чтобы соеденить HTML с PHP я воспользовался вашей статьёй и ввёл «DirectoryIndex index.html» в файл PHP! Всё заработало, но правильно ли я сделал?

    Работает, и хорошо, всё равно, когда будете выкладывать на хостинг, всё расположение будет изменено.

    А вы можете обьяснить как вы делали сайт? Как вы обьединяли HTML с PHP?

    Я писал свой движок. Вы не знаете даже основ PHP, поэтому даже не задумывайтесь об этом, ещё рано. Сначала изучите базовые вещи, а уже потом и будете заниматься сложными.

    Хех. Вот сейчас читаю, что я писал раньше и думаю какая фигня:) Сейчас уже свой движок написал, а раньше спрашивал как соединить html и php ))) Спасибо, Михаил. Благодаря Вам и Вашему сайту, я смог достичь такого успеха.

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Saved searches

    Use saved searches to filter your results more quickly

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

    Make an plain html page containing a directory listing

    License

    mafintosh/directory-index-html

    This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

    Name already in use

    A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

    Sign In Required

    Please sign in to use Codespaces.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio Code

    Your codespace will open once ready.

    There was a problem preparing your codespace, please try again.

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.md

    Make an plain html page containing a directory listing. Similar in look and feel to NGINX’s listing page.

    npm install directory-index-html 
    var toHTML = require('directory-index-html') var entries = [ name: 'test', size: 24424, mtime: new Date() >,  name: 'a-dir/', mtime: new Date() >] console.log(toHTML('/foo/bar', entries))

    var html = toHTML(dir, entries)

    Render a directory name and listing to an plain HTML string.

    dir should be a string containing the directory name.

    entries should be an array of entries that are similar to this

     name: 'name-of-file-or-dir', size: 42424, // size in bytes mtime: new Date() // when was this modified >

    To figure out if an entry is a directory the module will one of the following things:

    • Check if the path ends with a /
    • See if entry.type === ‘directory’
    • See if entry.mode specifies a directory

    There is a small demo server bundled in the repo that serves a directory listing of your current working directory.

    To try it out, run node demo.js and visit http://localhost:8080 .

    It should show something like this:

    Источник

    How to generate directory index files

    Recently I needed a simple utility to generate index files at briefcase.sleeplessbeastie.eu, so after a while, I came up with two simple solutions, each of which has different strengths and weaknesses.

    Apache directory theme#

    The easiest way is to use Apaxy, as it is a straightforward and beautiful solution.

    This solution can be quickly modified to provide a custom welcome message, icons, or style sheet. However, please note that it is not possible to alter the generated directory listing.

    Shell script#

    The second solution is slightly more complicated as it uses a custom shell script to generate index files but provides more control over generated HTML code.

    It uses the Twitter Bootstrap framework to provide good looking and responsive user interface, but you need to rerun the script after every change to update index files.

    #!/bin/bash # BASH script designed to generate index files using # Twitter Bootstrap [getbootstrap.com] # Notes: # * Script will ignore "img" and "css" directories and "index.html" file # * Remember to copy Twitter Bootstrap files (css,img) # Sample usage: # cd /var/www/downloads # make_index.sh # web root directory, # it will be used to generate URLs # "" - root directory # "/downloads" - '/downloads' subdirectory root_directory="/downloads" # template settings brand="sleeplessbeastie.eu" title="sleeplessbeastie.eu - briefcase" # generate header part of the HTML file function header < cat          
    $brand

    $title

    EOF > # generate footer part of the HTML file function footer < cat EOF > # create index file for each directory (ignore ./css and ./img directories) find . -type d -not -path "*/img" -not -path "*/css" | while read directory; do # remove "./" from the beginning of the path directory=$ # index file index_file=$directory/index.html # create/truncate index file : > $index_file # append header to the index file header >> $index_file # append "Up to higher level directory" link echo "
    > $index_file if [ "$directory" != "." ]; then echo "

    > $index_file echo "Up to higher level directory" >> $index_file else echo "


    " >> $index_file echo "> $index_file fi echo "

    " >> $index_file # append empty row echo "
    > $index_file # generate content content="" while read file do if [ -d "$directory/$file" ]; then content+="
    $file
    " else content+="
    $file
    " fi content+="
    " content+="
    " content+="
    " elif [ -f "$directory/$file" ]; then file_type=$(file -b "$directory/$file") file_size=$(du -h "$directory/$file" | cut -f1) content+="
    $file
    " else content+="
    $file
    " fi content+="
    " content+="
    " content+=" $file_type" content+="" content+="
    " fi done < <(ls -1 --group-directories-first $directory --ignore=index.html --ignore=css --ignore=img --ignore=make_index.sh) # append content to the index file echo $content >> $index_file # append footer to the index file footer >> $index_file done

    Follow me on Mastodon , check out source code ad GitHub

    Источник

    Читайте также:  Java directory relative path
    Оцените статью