- Directory Listing Configuration
- Trailing Slash Redirection
- Directory Indexes
- Directory Listings
- Excluding Files
- Some files aren’t listed
- Headers and Footers
- Styling the listing
- Extended example
- Apache Module mod_dir
- Directives
- DirectoryIndex Directive
- Example
- DirectorySlash Directive
- Security Warning
- FallbackResource Directive
- Comments
- Использование DirectoryIndex в .htaccess
- Комментарии ( 5 ):
Directory Listing Configuration
Here we describe various types of things that the server can send when you request a directory rather than an individual file.
Trailing Slash Redirection
If you request a directory without including the trailing slash in its name (i.e. http://example.com/dir rather than http://example.com/dir/ ), then Apache must send a redirect to add the trailing slash to the URL. This is necessary so relative hyperlinks will work in the resulting file.
For this to work, Apache must know the name of the server so that it can send a redirect back to itself. Normally, when UseCanonicalName is set off, the name supplied by the client in the Host HTTP request header is used. If UseCanonicalName is on, then you need to assure that ServerName is set correctly in order for this redirect to work.
Directory Indexes
When a directory is requested, Apache may be configured to send a particular file within that directory automatically. This is configured with the DirectoryIndex directive. It can list one or more files that Apache should search for in the directory, with the first existing file being returned to the client. For example:
DirectoryIndex index.html index.htm index.php welcome.html
Directory Listings
If no file from the DirectoryIndex directive can be located in the directory, then mod_autoindex can generate a listing of the directory contents. This is turned on and off using the Options directive. For example, to turn on directory listings for a particular directory, you can use:
To prevent directory listings (for security purposes, for example), you should remove the Indexes keyword from every Options directive in your configuration file. Or to prevent them only for a single directory, you can use:
Excluding Files
If you would like listings to be enabled, but you want to omit particular files, you can use the IndexIgnore directive. For example, to omit any filename starting with tmp and also the parent directory link (..), you could use:
Some files aren’t listed
When a directory listing is produced, certain files will not be shown, by default. Files and directories that have access restrictions placed on them, either by password or by address, will not be shown in a directory listing.
If you want these files to be listed, you will need to set IndexOptions ShowForbidden in the directory block in question. The ShowForbidden setting is only available in 2.2 and later.
Headers and Footers
The directives HeaderName and ReadmeName configure a file to be included, respectively, above and below the file listing. If no path is given, Apache will look for these files in the directory being listed. For example:
HeaderName header.html ReadmeName footer.html
A path starting in slash can be used if you want the same files included for all directories:
HeaderName /site/header.html ReadmeName /site/footer.html
Styling the listing
The directory listing is highly configurable. The IndexOptions directive gives lots of choices for different configurations and the IndexStyleSheet directive allows a CSS stylesheet to be specified. A typical configuration might look like:
IndexOptions FancyIndexing HTMLTable IndexStyleSheet /css/autoindex.css
Extended example
For a more complete example, including a configuration for the icons displayed with the files, see conf/extra/httpd-autoindex.conf as distributed with Apache httpd.
Apache Module mod_dir
The index of a directory can come from one of two sources:
- A file written by the user, typically called index.html . The DirectoryIndex directive sets the name of this file. This is controlled by mod_dir .
- Otherwise, a listing generated by the server. This is provided by mod_autoindex .
The two functions are separated so that you can completely remove (or replace) automatic index generation should you want to.
A «trailing slash» redirect is issued when the server receives a request for a URL http://servername/foo/dirname where dirname is a directory. Directories require a trailing slash, so mod_dir issues a redirect to http://servername/foo/dirname/ .
Directives
DirectoryIndex Directive
Description: | List of resources to look for when the client requests a directory |
---|---|
Syntax: | DirectoryIndex local-url [ local-url ] . |
Default: | DirectoryIndex index.html |
Context: | server config, virtual host, directory, .htaccess |
Override: | Indexes |
Status: | Base |
Module: | mod_dir |
The DirectoryIndex directive sets the list of resources to look for, when the client requests an index of the directory by specifying a / at the end of the directory name. Local-url is the (%-encoded) URL of a document on the server relative to the requested directory; it is usually the name of a file in the directory. Several URLs may be given, in which case the server will return the first one that it finds. If none of the resources exist and the Indexes option is set, the server will generate its own listing of the directory.
Example
then a request for http://example.com/docs/ would return http://example.com/docs/index.html if it exists, or would list the directory if it did not.
Note that the documents do not need to be relative to the directory;
DirectoryIndex index.html index.txt /cgi-bin/index.pl
would cause the CGI script /cgi-bin/index.pl to be executed if neither index.html or index.txt existed in a directory.
Note: Multiple DirectoryIndex directives within the same context will add to the list of resources to look for rather than replace:
# Example A: Set index.html as an index page, then add index.php to that list as well.DirectoryIndex index.html DirectoryIndex index.php # Example B: This is identical to example A, except it's done with a single directive.DirectoryIndex index.html index.php
DirectorySlash Directive
Description: | Toggle trailing slash redirects on or off |
---|---|
Syntax: | DirectorySlash On|Off |
Default: | DirectorySlash On |
Context: | server config, virtual host, directory, .htaccess |
Override: | Indexes |
Status: | Base |
Module: | mod_dir |
Compatibility: | Available in version 2.0.51 and later |
The DirectorySlash directive determines whether mod_dir should fixup URLs pointing to a directory or not.
Typically if a user requests a resource without a trailing slash, which points to a directory, mod_dir redirects him to the same resource, but with trailing slash for some good reasons:
- The user is finally requesting the canonical URL of the resource
- mod_autoindex works correctly. Since it doesn’t emit the path in the link, it would point to the wrong path.
- DirectoryIndex will be evaluated only for directories requested with trailing slash.
- Relative URL references inside html pages will work correctly.
If you don’t want this effect and the reasons above don’t apply to you, you can turn off the redirect as shown below. However, be aware that there are possible security implications to doing this.
# see security warning below!
DirectorySlash Off
SetHandler some-handler
Security Warning
Turning off the trailing slash redirect may result in an information disclosure. Consider a situation where mod_autoindex is active ( Options +Indexes ) and DirectoryIndex is set to a valid resource (say, index.html ) and there’s no other special handler defined for that URL. In this case a request with a trailing slash would show the index.html file. But a request without trailing slash would list the directory contents.
FallbackResource Directive
Description: | Define a default URL for requests that don’t map to a file |
---|---|
Syntax: | FallbackResource disabled | local-url |
Default: | None — httpd will return 404 (Not Found) |
Context: | server config, virtual host, directory, .htaccess |
Override: | Indexes |
Status: | Base |
Module: | mod_dir |
Compatibility: | Apache HTTP Server 2.2.16 and later — The disabled argument is supported since 2.2.24 |
Use this to set a handler for any URL that doesn’t map to anything in your filesystem, and would otherwise return HTTP 404 (Not Found). For example
will cause requests for non-existent files to be handled by not-404.php , while requests for files that exist are unaffected.
It is frequently desirable to have a single file or resource handle all requests to a particular directory, except those requests that correspond to an existing file or script. This is often referred to as a ‘front controller.’
In earlier versions of httpd, this effect typically required mod_rewrite , and the use of the -f and -d tests for file and directory existence. This now requires only one line of configuration.
Existing files, such as images, css files, and so on, will be served normally.
Use the disabled argument to disable that feature if inheritance from a parent directory is not desired.
In a sub-URI, such as http://example.com/blog/ this sub-URI has to be supplied as local-url :
Comments
Notice:
This is not a Q&A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed again by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Libera.chat, or sent to our mailing lists.
Copyright 2018 The Apache Software Foundation.
Licensed under the Apache License, Version 2.0.
Использование DirectoryIndex в .htaccess
Все Вы знаете, что страница «index.php» открывается по умолчанию. То есть когда Вы указываете в URL путь к каталогу, например так: «http://site.ru/mydir/«, то сервером возвращается файл «index.php» из этого каталога. Если этого файла нет, то возвращается «index.html» или «index.htm«. Если и их нет, то выводится либо содержимое каталога, либо ошибка 403 («Forbidden«), в зависимости от настроек сервера. Но иногда требуется переопределить страницу по умолчанию и возвращать из каталога совсем другой файл. Именно для такой цели и используется 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.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - 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 Русаков Михаил Юрьевич. Все права защищены.