developer/ 40755 0 0 0 10422374002 10067 5ustar 0 0 faq/ 40755 0 0 0 10422374002 6651 5ustar 0 0 howto/ 40755 0 0 0 10422374002 7242 5ustar 0 0 images/ 40755 0 0 0 10422374002 7347 5ustar 0 0 misc/ 40755 0 0 0 10422374002 7035 5ustar 0 0 mod/ 40755 0 0 0 10422374002 6661 5ustar 0 0 platform/ 40755 0 0 0 10422374002 7726 5ustar 0 0 programs/ 40755 0 0 0 10422374002 7734 5ustar 0 0 rewrite/ 40755 0 0 0 10422374002 7563 5ustar 0 0 ssl/ 40755 0 0 0 10422374002 6703 5ustar 0 0 style/ 40755 0 0 0 10422374002 7242 5ustar 0 0 style/_generated/ 40755 0 0 0 10422374002 11337 5ustar 0 0 style/css/ 40755 0 0 0 10422373543 10043 5ustar 0 0 style/lang/ 40755 0 0 0 10422374002 10163 5ustar 0 0 style/latex/ 40755 0 0 0 10422374002 10357 5ustar 0 0 style/xsl/ 40755 0 0 0 10422374002 10050 5ustar 0 0 style/xsl/util/ 40755 0 0 0 10422374002 11025 5ustar 0 0 vhosts/ 40755 0 0 0 10422374002 7430 5ustar 0 0 bind.html100644 0 0 21541 10422374001 10023 0ustar 0 0 バインド - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

バインド

Apache が使用するアドレスとポートの設定をします。

参照

top

概要

Apache は起動時に、ローカルマシンのあるポートおよびアドレス に対して接続し、リクエストが来るのを待ちます。 デフォルトではマシンのすべてのアドレスに対して listen します。 しかしながら、特定のポートか、特定のアドレスのみか、 またはそれらの組み合わせのいずれかを listen するようにする必要があります。 これは、異なる IP アドレス、ホスト名、ポートに対する Apache の応答方法を決定するバーチャルホスト機能と組み合わせて使われます。

Listen ディレクティブで、特定のポートやアドレス・ポートの組からのみ入ってくる リクエストを受け付けるようにできます。 もしポート番号のみが Listen ディレクティブで指定された場合は、 すべてのインターフェースの与えられたポート番号を listen します。 IP アドレスがポート番号と同時に与えられた場合は、 サーバは与えられたポートとインターフェースを listen します。 複数の Listen ディレクティブを用いて いくつかの listen するアドレスとポートを指定できます。 サーバはリストされたアドレスやポートからのすべてのリクエストに 対して応答します。

たとえば、ポート 80 と 8000 の両方に対しての接続を受け付けるには

Listen 80
Listen 8000

とします。 二つの指定されたインタフェースとポート番号に対しての接続を受け付けるには、

Listen 192.170.2.1:80
Listen 192.170.2.5:8000

とします。 IPv6 アドレスは、角括弧で次の例のように囲まなければいけません。

Listen [2001:db8::a00:20ff:fea7:ccea]:80

top

IPv6 の特記事項

多くのプラットホームで IPv6 がサポートされてきていて、 APR はこれらのほとんどで IPv6 をサポートしているので、 Apache は IPv6 ソケットを割り当てて IPv6 経由で送られてきたリクエストを扱うことができます。

IPv6 ソケットが IPv4 と IPv6 コネクションの両方を扱うことができるか どうかは、Apache 管理者にとって厄介な問題です。 IPv4 コネクションを IPv6 ソケットで扱う場合は、 IPv4 マップされた IPv6 アドレスを使用していて、 ほとんどのプラットホームではデフォルトで使用可能ですが、 FreeBSD, NetBSD, OpenBSD では、システム全体としてのポリシーとの整合性から、 デフォルトでは使用不可に設定されています。 これらのデフォルトで使用不可のプラットホームであっても、 特別な configure の 設定パラメータで Apache の挙動を変化させることができます。

一方で、Linux や Tru64 といったプラットホームで IPv4 と IPv6 の両方を扱うには、マップトアドレスを使用する以外の方法はありません。 IPv4 と IPv6 のコネクションを最小限のソケットで扱いたいのであれば、 IPv4 マップの IPv6 アドレスを使用する必要があり、 --enable-v4-mapped configure オプションを指定します。

--enable-v4-mapped は、 FreeBSD, NetBSD, OpenBSD 以外の全てのプラットホームでのデフォルトです。 ですから、おそらくお手元の Apache はこの設定でビルドされているでしょう。

プラットフォームや APR が何をサポートするかに関わらず、 IPv4 コネクションのみを扱うようにしたい場合は、 次の例のように全ての Listen ディレクティブで IPv4 アドレスを指定してください。

Listen 0.0.0.0:80
Listen 192.170.2.1:80

条件を満たすプラットホームで、Apache が IPv4 と IPv6 のコネクションを個別のソケットで扱うようにしたい場合 (つまり IPv4 マップのアドレスを無効にしたい場合) は、--disable-v4-mapped configure オプションを指定して、次のように個別指定の Listen ディレクティブを使用してください。 --disable-v4-mapped は、 FreeBSD, NetBSD, OpenBSD プラットホームでのデフォルトです。

top

バーチャルホストに対してどう働くのか

Listen でバーチャルホストが実装されるわけではありません。 Listen は単にメインサーバにどのアドレスとポートを listen すべきかを 教えるだけです。 <VirtualHost> ディレクティブが使われない場合は、 受け入れたリクエストすべてに対して全く同じ挙動をします。 しかしながら <VirtualHost> を使って、 一つ以上のアドレスやポートに対して異なる挙動をするように 指定することができます。 VirtualHost を実装するには、使用するアドレスとポートを まず初めにサーバに通知しなければなりません。 そして、その指定したアドレスとポートでの このバーチャルホストの挙動を設定するために、 <VirtualHost> セクションを作ります。もし <VirtualHost> が listen していないアドレスとポートに対して 設定されてしまうと、 それにはアクセスできないということに注意してください。

caching.html100644 0 0 112351 10422374001 10523 0ustar 0 0 Caching Guide - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2

Caching Guide

This document supplements the mod_cache, mod_disk_cache, mod_mem_cache, mod_file_cache and htcacheclean reference documentation. It describes how to use Apache's caching features to accelerate web and proxy serving, while avoiding common problems and misconfigurations.

top

Introduction

As of Apache HTTP server version 2.2 mod_cache and mod_file_cache are no longer marked experimental and are considered suitable for production use. These caching architectures provide a powerful means to accelerate HTTP handling, both as an origin webserver and as a proxy.

mod_cache and its provider modules mod_mem_cache and mod_disk_cache provide intelligent, HTTP-aware caching. The content itself is stored in the cache, and mod_cache aims to honour all of the various HTTP headers and options that control the cachability of content. It can handle both local and proxied content. mod_cache is aimed at both simple and complex caching configurations, where you are dealing with proxied content, dynamic local content or have a need to speed up access to local files which change with time.

mod_file_cache on the other hand presents a more basic, but sometimes useful, form of caching. Rather than maintain the complexity of actively ensuring the cachability of URLs, mod_file_cache offers file-handle and memory-mapping tricks to keep a cache of files as they were when Apache was last started. As such, mod_file_cache is aimed at improving the access time to local static files which do not change very often.

As mod_file_cache presents a relatively simple caching implementation, apart from the specific sections on CacheFile and MMapStatic, the explanations in this guide cover the mod_cache caching architecture.

To get the most from this document, you should be familiar with the basics of HTTP, and have read the Users' Guides to Mapping URLs to the Filesystem and Content negotiation.

top

Caching Overview

There are two main stages in mod_cache that can occur in the lifetime of a request. First, mod_cache is a URL mapping module, which means that if a URL has been cached, and the cached version of that URL has not expired, the request will be served directly by mod_cache.

This means that any other stages that might ordinarily happen in the process of serving a request -- for example being handled by mod_proxy, or mod_rewrite -- won't happen. But then this is the point of caching content in the first place.

If the URL is not found within the cache, mod_cache will add a filter to the request handling. After Apache has located the content by the usual means, the filter will be run as the content is served. If the content is determined to be cacheable, the content will be saved to the cache for future serving.

If the URL is found within the cache, but also found to have expired, the filter is added anyway, but mod_cache will create a conditional request to the backend, to determine if the cached version is still current. If the cached version is still current, its meta-information will be updated and the request will be served from the cache. If the cached version is no longer current, the cached version will be deleted and the filter will save the updated content to the cache as it is served.

Improving Cache Hits

When caching locally generated content, ensuring that UseCanonicalName is set to On can dramatically improve the ratio of cache hits. This is because the hostname of the virtual-host serving the content forms a part of the cache key. With the setting set to On virtual-hosts with multiple server names or aliases will not produce differently cached entities, and instead content will be cached as per the canonical hostname.

Because caching is performed within the URL to filename translation phase, cached documents will only be served in response to URL requests. Ordinarily this is of little consequence, but there is one circumstance in which it matters: If you are using Server Side Includes;

<!-- The following include can be cached -->
<!--#include virtual="/footer.html" --> 

<!-- The following include can not be cached -->
<!--#include file="/path/to/footer.html" -->

If you are using Server Side Includes, and want the benefit of speedy serves from the cache, you should use virtual include types.

Expiry Periods

The default expiry period for cached entities is one hour, however this can be easily over-ridden by using the CacheDefaultExpire directive. This default is only used when the original source of the content does not specify an expire time or time of last modification.

If a response does not include an Expires header but does include a Last-Modified header, mod_cache can infer an expiry period based on the use of the CacheLastModifiedFactor directive.

For local content, mod_expires may be used to fine-tune the expiry period.

The maximum expiry period may also be controlled by using the CacheMaxExpire.

A Brief Guide to Conditional Requests

When content expires from the cache and is re-requested from the backend or content provider, rather than pass on the original request, Aoache will use a conditional request instead.

HTTP offers a number of headers which allow a client, or cache to discern between different versions of the same content. For example if a resource was served with an "Etag:" header, it is possible to make a conditional request with an "If-Match:" header. If a resource was served with a "Last-Modified:" header it is possible to make a conditional request with an "If-Modified-Since:" header, and so on.

When such a conditional request is made, the response differs depending on whether the content matches the conditions. If a request is made with an "If-Modified-Since:" header, and the content has not been modified since the time indicated in the request then a terse "304 Not Modified" response is issued.

If the content has changed, then it is served as if the request were not conditional to begin with.

The benefits of conditional requests in relation to caching are twofold. Firstly, when making such a request to the backend, if the content from the backend matches the content in the store, this can be determined easily and without the overhead of transferring the entire resource.

Secondly, conditional requests are usually less strenuous on the backend. For static files, typically all that is involved is a call to stat() or similar system call, to see if the file has changed in size or modification time. As such, even if Apache is caching local content, even expired content may still be served faster from the cache if it has not changed. As long as reading from the cache store is faster than reading from the backend (e.g. an in-memory cache compared to reading from disk).

What Can be Cached?

As mentioned already, the two styles of caching in Apache work differently, mod_file_cache caching maintains file contents as they were when Apache was started. When a request is made for a file that is cached by this module, it is intercepted and the cached file is served.

mod_cache caching on the other hand is more complex. When serving a request, if it has not been cached previously, the caching module will determine if the content is cacheable. The conditions for determining cachability of a response are;

  1. Caching must be enabled for this URL. See the CacheEnable and CacheDisable directives.
  2. The response must have a HTTP status code of 200, 203, 300, 301 or 410.
  3. The request must be a HTTP GET request.
  4. If the request contains an "Authorization:" header, the response will not be cached.
  5. If the response contains an "Authorization:" header, it must also contain an "s-maxage", "must-revalidate" or "public" option in the "Cache-Control:" header.
  6. If the URL included a query string (e.g. from a HTML form GET method) it will not be cached unless the response includes an "Expires:" header, as per RFC2616 section 13.9.
  7. If the response has a status of 200 (OK), the response must also include at least one of the "Etag", "Last-Modified" or the "Expires" headers, unless the CacheIgnoreNoLastMod directive has been used to require otherwise.
  8. If the response includes the "private" option in a "Cache-Control:" header, it will not be stored unless the CacheStorePrivate has been used to require otherwise.
  9. Likewise, if the response includes the "no-store" option in a "Cache-Control:" header, it will not be stored unless the CacheStoreNoStore has been used.
  10. A response will not be stored if it includes a "Vary:" header containing the match-all "*".

What Should Not be Cached?

In short, any content which is highly time-sensitive, or which varies depending on the particulars of the request that are not covered by HTTP negotiation, should not be cached.

If you have dynamic content which changes depending on the IP address of the requester, or changes every 5 minutes, it should almost certainly not be cached.

If on the other hand, the content served differs depending on the values of various HTTP headers, it is possible that it might be possible to cache it intelligently through the use of a "Vary" header.

Variable/Negotiated Content

If a response with a "Vary" header is received by mod_cache when requesting content by the backend it will attempt to handle it intelligently. If possible, mod_cache will detect the headers attributed in the "Vary" response in future requests and serve the correct cached response.

If for example, a response is received with a vary header such as;

Vary: negotiate,accept-language,accept-charset

mod_cache will only serve the cached content to requesters with matching accept-language and accept-charset headers matching those of the original request.

top

Security Considerations

Authorisation, Access & and Control

Using mod_cache is very much like having a built in reverse-proxy. Requests will be served by the caching module unless it determines that the backend should be queried. When caching local resources, this drastically changes the security model of Apache.

As traversing a filesystem hierarchy to examine potential .htaccess files would be a very expensive operation, partially defeating the point of caching (to speed up requests), mod_cache makes no decision about whether a cached entity is authorised for serving. In other words; if mod_cache has cached some content, it will be served from the cache as long as that content has not expired.

If, for example, your configuration permits access to a resource by IP address you should ensure that this content is not cached. You can do this by using the CacheDisable directive, or mod_expires. Left unchecked, mod_cache - very much like a reverse proxy - would cache the content when served and then serve it to any client, on any IP address.

Local exploits

As requests to end-users can be served from the cache, the cache itself can become a target for those wishing to deface or interfere with content. It is important to bear in mind that the cache must at all times be writable by the user which Apache is running as. This is in stark contrast to the usually recommended situation of maintaining all content unwritable by the Apache user.

If the Apache user is compromised, for example through a flaw in a CGI process, it is possible that the cache may be targeted. When using mod_disk_cache, it is relatively easy to insert or modify a cached entity.

This presents a somewhat elevated risk in comparison to the other types of attack it is possible to make as the Apache user. If you are using mod_disk_cache you should bear this in mind - ensure you upgrade Apache when security upgrades are announced and run CGI processes as a non-Apache user using suEXEC if possible.

Cache Poisoning

When running Apache as a caching proxy server, there is also the potential for so-called cache poisoning. Cache Poisoning is a broad term for attacks in which an attacker causes the proxy server to retrieve incorrect (and usually undesirable) content from the backend.

For example if the DNS servers used by your system running Apache are vulnerable to DNS cache poisoning, an attacker may be able to control where Apache connects to when requesting content from the origin server. Another example is so-called HTTP request-smuggling attacks.

This document is not the correct place for an in-depth discussion of HTTP request smuggling (instead, try your favourite search engine) however it is important to be aware that it is possible to make a series of requests, and to exploit a vulnerability on an origin webserver such that the attacker can entirely control the content retrieved by the proxy.

top

File-Handle Caching

The act of opening a file can itself be a source of delay, particularly on network filesystems. By maintaining a cache of open file descriptors for commonly served files, Apache can avoid this delay. Currently Apache provides two different implementations of File-Handle Caching.

CacheFile

The most basic form of caching present in Apache is the file-handle caching provided by mod_file_cache. Rather than caching file-contents, this cache maintains a table of open file descriptors. Files to be cached in this manner are specified in the configuration file using the CacheFile directive.

The CacheFile directive instructs Apache to open the file when Apache is started and to re-use this file-handle for all subsequent access to this file.

CacheFile /usr/local/apache2/htdocs/index.html

If you intend to cache a large number of files in this manner, you must ensure that your operating system's limit for the number of open files is set appropriately.

Although using CacheFile does not cause the file-contents to be cached per-se, it does mean that if the file changes while Apache is running these changes will not be picked up. The file will be consistently served as it was when Apache was started.

If the file is removed while Apache is running, Apache will continue to maintain an open file descriptor and serve the file as it was when Apache was started. This usually also means that although the file will have been deleted, and not show up on the filesystem, extra free space will not be recovered until Apache is stopped and the file descriptor closed.

CacheEnable fd

mod_mem_cache also provides its own file-handle caching scheme, which can be enabled via the CacheEnable directive.

CacheEnable fd /

As with all of mod_cache this type of file-handle caching is intelligent, and handles will not be maintained beyond the expiry time of the cached content.

top

In-Memory Caching

Serving directly from system memory is universally the fastest method of serving content. Reading files from a disk controller or, even worse, from a remote network is orders of magnitude slower. Disk controllers usually involve physical processes, and network access is limited by your available bandwidth. Memory access on the other hand can take mere nano-seconds.

System memory isn't cheap though, byte for byte it's by far the most expensive type of storage and it's important to ensure that it is used efficiently. By caching files in memory you decrease the amount of memory available on the system. As we'll see, in the case of operating system caching, this is not so much of an issue, but when using Apache's own in-memory caching it is important to make sure that you do not allocate too much memory to a cache. Otherwise the system will be forced to swap out memory, which will likely degrade performance.

Operating System Caching

Almost all modern operating systems cache file-data in memory managed directly by the kernel. This is a powerful feature, and for the most part operating systems get it right. For example, on Linux, let's look at the difference in the time it takes to read a file for the first time and the second time;

colm@coroebus:~$ time cat testfile > /dev/null
real    0m0.065s
user    0m0.000s
sys     0m0.001s
colm@coroebus:~$ time cat testfile > /dev/null
real    0m0.003s
user    0m0.003s
sys     0m0.000s

Even for this small file, there is a huge difference in the amount of time it takes to read the file. This is because the kernel has cached the file contents in memory.

By ensuring there is "spare" memory on your system, you can ensure that more and more file-contents will be stored in this cache. This can be a very efficient means of in-memory caching, and involves no extra configuration of Apache at all.

Additionally, because the operating system knows when files are deleted or modified, it can automatically remove file contents from the cache when neccessary. This is a big advantage over Apache's in-memory caching which has no way of knowing when a file has changed.

Despite the performance and advantages of automatic operating system caching there are some circumstances in which in-memory caching may be better performed by Apache.

Firstly, an operating system can only cache files it knows about. If you are running Apache as a proxy server, the files you are caching are not locally stored but remotely served. If you still want the unbeatable speed of in-memory caching, Apache's own memory caching is needed.

MMapStatic Caching

mod_file_cache provides the MMapStatic directive, which allows you to have Apache map a static file's contents into memory at start time (using the mmap system call). Apache will use the in-memory contents for all subsequent accesses to this file.

MMapStatic /usr/local/apache2/htdocs/index.html

As with the CacheFile directive, any changes in these files will not be picked up by Apache after it has started.

The MMapStatic directive does not keep track of how much memory it allocates, so you must ensure not to over-use the directive. Each Apache child process will replicate this memory, so it is critically important to ensure that the files mapped are not so large as to cause the system to swap memory.

mod_mem_cache Caching

mod_mem_cache provides a HTTP-aware intelligent in-memory cache. It also uses heap memory directly, which means that even if MMap is not supported on your system, mod_mem_cache may still be able to perform caching.

Caching of this type is enabled via;

# Enable memory caching
CacheEnable mem /

# Limit the size of the cache to 1 Megabyte
MCacheSize 1024
top

Disk-based Caching

mod_disk_cache provides a disk-based caching mechanism for mod_cache. As with mod_mem_cache this cache is intelligent and content will be served from the cache only as long as it is considered valid.

Typically the module will be configured as so;

CacheRoot   /var/cache/apache/
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1

Importantly, as the cached files are locally stored, operating system in-memory caching will typically be applied to their access also. So although the files are stored on disk, if they are frequently accessed it is likely the operating system will ensure that they are actually served from memory.

Understanding the Cache-Store

To store items in the cache, mod_disk_cache creates a 22 character hash of the url being requested. Thie hash incorporates the hostname, protocol, port, path and any CGI arguments to the URL, to ensure that multiple URLs do not collide.

Each character may be any one of 64-different characters, which mean that overall there are 22^64 possible hashes. For example, a URL might be hashed to xyTGxSMO2b68mBCykqkp1w. This hash is used as a prefix for the naming of the files specific to that url within the cache, however first it is split up into directories as per the CacheDirLevels and CacheDirLength directives.

CacheDirLevels specifies how many levels of subdirectory there should be, and CacheDirLength specifies how many characters should be in each directory. With the example settings given above, the hash would be turned into a filename prefix as /var/cache/apache/x/y/TGxSMO2b68mBCykqkp1w.

The overall aim of this technique is to reduce the number of subdirectories or files that may be in a particular directory, as most file-systems slow down as this number increases. With setting of "1" for CacheDirLength there can at most be 64 subdirectories at any particular level. With a setting of 2 there can be 64 * 64 subdirectories, and so on. Unless you have a good reason not to, using a setting of "1" for CacheDirLength is recommended.

Setting CacheDirLevels depends on how many files you anticipate to store in the cache. With the setting of "2" used in the above example, a grand total of 4096 subdirectories can ultimately be created. With 1 million files cached, this works out at roughly 245 cached urls per directory.

Each url uses at least two files in the cache-store. Typically there is a ".header" file, which includes meta-information about the url, such as when it is due to expire and a ".data" file which is a verbatim copy of the content to be served.

In the case of a content negotiated via the "Vary" header, a ".vary" directory will be created for the url in question. This directory will have multiple ".data" files corresponding to the differently negotiated content.

Maintaining the Disk Cache

Although mod_disk_cache will remove cached content as it is expired, it does not maintain any information on the total size of the cache or how little free space may be left.

Instead, provided with Apache is the htcacheclean tool which, as the name suggests, allows you to clean the cache periodically. Determining how frequently to run htcacheclean and what target size to use for the cache is somewhat complex and trial and error may be needed to select optimal values.

htcacheclean has two modes of operation. It can be run as persistent daemon, or periodically from cron. htcacheclean can take up to an hour or more to process very large (tens of gigabytes) caches and if you are running it from cron it is recommended that you determine how long a typical run takes, to avoid running more than one instance at a time.


Figure 1: Typical cache growth / clean sequence.

Because mod_disk_cache does not itself pay attention to how much space is used you should ensure that htcacheclean is configured to leave enough "grow room" following a clean.

configuring.html100644 0 0 26201 10422374001 11417 0ustar 0 0 設定ファイル - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

設定ファイル

この文書では、Apache HTTP サーバを設定するのに使用するファイルについて 記述しています。

top

メインの設定ファイル

Apache は ディレクティブ を設定ファイルに平文で書くことにより設定します。 メインの設定ファイルは普通は httpd.conf という名前です。 このファイルの位置はコンパイル時に設定されますが、コマンドラインの -f フラグにより上書きできます。 また、他の設定ファイルを Include ディレクティブによって追加でき、ワイルドカードを使用して多数の 設定ファイルを追加することができます。 どんなディレクティブも、これらの設定ファイルどれにでも入れることができます。 Apache は起動時か再起動時のみメイン設定ファイルの変更を認識します。

サーバは MIME ドキュメントタイプを含んでいるファイルも読み込みます。ファイル名は TypesConfig で設定され、デフォルトでは mime.types になっています。

top

設定ファイルの構文

Apache の設定ファイルは 1 行に 1 つのディレクティブからなります。 バックスラッシュ "\" はディレクティブが次の行に継続していることを 示すために行の最後の文字として使われているかもしれません。 行の最後とバックスラッシュの間に他の文字や空白があってはいけません。

設定ファイルのディレクティブは大文字小文字を区別しませんが、 引数にはしばしば区別するものがあります。ハッシュ文字 "#" で始まる行はコメントと見なされて無視されます。 設定ディレクティブの後の行ではコメントが含まれていてはいけません。ディレクティブの前の空行と空白は無視されますので、 わかりやすくするためにディレクティブをインデントしても構いません。

設定ファイルの構文エラーは、 apachectl configtest かコマンドラインオプション -t を使って調べられます。

top

モジュール

Apache はモジュール化されたサーバです。 コアサーバには最も基本的な機能だけが含まれています。拡張機能は Apache にロードされるモジュールとして利用可能です。デフォルトでは、コンパイル時にモジュールの Base セット (基本セット) が サーバに含まれます。サーバが動的ロードモジュールを使うようにコンパイルされている場合は、 モジュールを別にコンパイルして、いつでも LoadModule ディレクティブを使って追加できます。 そうでない場合は、モジュールの追加や削除をするためには Apache を再コンパイルする必要があります。設定ディレクティブは <IfModule> ブロックに入れることで特定のモジュールが存在するときだけ 設定ファイルに含まれるようにすることができます。

コマンドラインオプション -l を使って現時点で どのモジュールがサーバにコンパイルされているかを知ることができます。

top

ディレクティブの適用範囲

メイン設定ファイルにあるディレクティブはサーバ全体に適用されます。 サーバの一部分の設定だけを変更したい場合は <Directory>, <DirectoryMatch>, <Files>, <FilesMatch>, <Location>, <LocationMatch> セクションの中に置くことで適用範囲を決められます。 これらのセクションはその中にあるディレクティブの適用範囲を 特定のファイルシステムの位置や URL に限定します。 非常に細粒度の設定を可能にするために、 セクションを入れ子にすることもできます。

Apache は同時に多くの違うウェブサイトを扱う能力があります。 これは バーチャルホスト と呼ばれています。 特定のウェブサイトにのみ適用されるようにするために、 ディレクティブは <VirtualHost> セクションの中に置くことでも適用範囲を変えることができます。

ほとんどのディレクティブはどのセクションにでも書けますが、 中にはコンテキストによっては意味をなさないものもあります。 例えば、プロセスの作成を制御しているディレクティブはメインサーバの コンテキストにのみ書くことができます。 どのディレクティブをどのセクションに書くことができるかを知るためには ディレクティブの コンテキスト を調べてください。詳しい情報は、 Directory, Location, Files セクションの動作法にあります。

top

.htaccess ファイル

Apache ではウェブツリーの中に置かれた特別なファイルを使って 非中央集権的な設定管理をできます。その特別なファイルは普通は .htaccess という名前で、 AccessFileName ディレクティブでどんな名前にでも指定できます。 .htaccess ファイルに書かれたディレクティブはファイルを置いた ディレクトリとその全てのサブディレクトリに適用されます。 .htaccess ファイルは、メインの設定ファイルと同じ 構文を使います。 .htaccess ファイルはすべてのリクエストで読み込まれるため、 変更はすぐに反映されます。

どのディレクティブが .htaccess ファイルに書けるかを調べるには、ディレクティブのコンテキスト を調べてください。サーバ管理者はさらにメイン設定ファイルの AllowOverride を設定することでどのディレクティブを .htaccess ファイルに書けるようにするかを制御することができます。

.htaccess ファイルに関する詳しい情報は .htaccess チュートリアル を参照してください。

content-negotiation.html100644 0 0 73750 10422374001 13110 0ustar 0 0 コンテントネゴシエーション - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

コンテントネゴシエーション

Apache は HTTP/1.1 の規格に記述されているコンテントネゴシエーションを サポートしています。 ブラウザにより提供されたメディアタイプ、 言語、文字セット、エンコーディングの優先傾向に基づいて、 最適なリソースの表現を選択できます。 また、不完全なネゴシエーション情報を送ってくるブラウザからのリクエストを もっと賢く取り扱えるよう、いくつか機能も実装してあります。

コンテントネゴシエーションは mod_negotiation モジュールによって提供されていて、デフォルトで組み込まれています。

top

コンテントネゴシエーションについて

リソースは、幾つか異なった表現で利用できる場合があります。 例えば、異なる言語や異なるメディアタイプ、 またはそれらの組み合わせで利用できるかも知れません。 もっとも適した選択をする方法の一つには、インデックスページを ユーザに見せて、ユーザに選んでもらう方法があります。 しかし、サーバが自動的に選ぶことができる場合が多くあります。 これは、ブラウザがリクエスト毎に、 どの表現を嗜好するかという情報を送ることで動作しています。 例えばブラウザは、可能ならフランス語で情報を見たい、 不可能ならその代わりに英語でもよいと、 自分の嗜好を知らせることができます。 ブラウザはリクエストのヘッダで自分の優先傾向を知らせます。 フランス語のみの表現を要求する場合は、ブラウザは次を送ります。

Accept-Language: fr

この優先傾向は、選択可能な表現が存在して、 言語によって様々な表現がある場合にのみ適用される ということに注意してください。

もっと複雑なリクエストの例を挙げましょう。 このブラウザはフランス語と英語を受け付ける、しかしフランス語を好む、 そして様々なメディアタイプを受け付けるが、 プレインテキストや他のタイプよりは HTML を好む、 他のメディアタイプよりは GIF や JPEG を好む、しかし最終手段として 他のメディアタイプも受け付ける、と設定されています。

Accept-Language: fr; q=1.0, en; q=0.5
Accept: text/html; q=1.0, text/*; q=0.8, image/gif; q=0.6, image/jpeg; q=0.6, image/*; q=0.5, */*; q=0.1

Apache は HTTP/1.1 規格で定義されている 'server driven' コンテントネゴシエーションをサポートしています。 Accept, Accept-Language, Accept-Charset, Accept-Encoding リクエストヘッダを完全にサポートしています。Apache は 'transparent' コンテントネゴシエーションもサポートしていますが、 これは RFC 2295 と RFC 2296 で定義されている試験的な ネゴシエーションプロトコルです。 これらの RFCで定義されている 'feature negotiation' はサポートしていません。

リソースとは URI で特定される概念上のもののことです (RFC 2396)。 Apache のような HTTP サーバは、その名前空間の中での リソースの表現へのアクセスを提供します。 それぞれの表現は 定義されたメディアタイプ、文字セット、エンコーディング等の 付属した、バイト列の形式です。 それぞれのリソースはある時点で 0 個、1 個、それ以上の表現と 関連付けられる可能性があります。複数の表現が利用できる場合は、 リソースはネゴシエーション可能であるとされ、 個々の表現は variant と呼ばれます。 ネゴシエーション可能なリソースの variant が異なる、 その状態を指して、 ネゴシエーションの次元と呼びます。

top

Apache におけるネゴシエーション

リソースをネゴシエーションするためには、 サーバは variant それぞれについての情報を知っておく必要があります。 これは以下の二つの方法のどちらかで行われます。

type-map ファイルを使う

タイプマップは type-map ハンドラ (もしくは、古い Apache の設定と下位互換である MIME タイプ application/x-type-map) に関連付けられたドキュメントです。 この機能を使うためには、あるファイルの拡張子を type-map として定義するようなハンドラを、 設定ファイル中に置く必要があることに注意してください。 これは

AddHandler type-map .var

をサーバ設定ファイル中に書くことが一番良い方法です。

タイプマップファイルは記述するリソースと同じ名前を持っていて、 利用可能な variant それぞれのエントリを持っている必要があります。 そして、このエントリは連続した HTTP のヘッダ行で構成されます。 異なる variant のためのエントリは空行で区切られています。 エントリ中に空行が複数あってはいけません。 習慣的には、マップファイルは全体を結合したもののエントリから始まります (しかしこれは必須ではなく、あったとしても無視されるものです)。 次に例を示します。このファイルはリソース foo を記述しているので、foo.var という名前になります。

URI: foo

URI: foo.en.html
Content-type: text/html
Content-language: en

URI: foo.fr.de.html
Content-type: text/html;charset=iso-8859-2
Content-language: fr, de

たとえ MultiViews を使用するようになっていたとしても、 ファイル名の拡張子よりタイプマップの方が優先権を持つということにも 注意してください。 variant の品質が違うときは、この画像のように (JPEG, GIF, ASCII アートがあります) メディアタイプの "qs" パラメータで指定されます。

URI: foo

URI: foo.jpeg
Content-type: image/jpeg; qs=0.8

URI: foo.gif
Content-type: image/gif; qs=0.5

URI: foo.txt
Content-type: text/plain; qs=0.01

qs 値の範囲は 0.000 から 1.000 です。qs 値が 0.000 の variant は決して 選択されないことに注意してください。'qs' 値のない variant は qs 値 1.0 を 与えられます。qs パラメータはクライアントの能力に関係無く、他の variant と 比較したときの variant の相対的な「品質」を示します。 例えば、写真を表現しようとしているときは JPEG ファイルの方が普通は ASCII ファイルよりも高い品質になります。しかし、リソースが元々 ASCII アートで表現されているときは、ASCII ファイルの 方が JPEG ファイルよりも高い品質になります。このように、qs は 表現されるリソースの性質によって variant 毎に特有の値を取ります。

認識されるヘッダの一覧は mod_negotiation ドキュメントにあります。

Multiviews

MultiViews はディレクトリ毎のオプションで、 httpd.confファイルの <Directory>, <Location>, <Files> セクション中や、(AllowOverride が適切な値に 設定されていると) .htaccess ファイルで Options ディレクティブによって設定することができます。 Options AllMultiViews をセットしないことに注意してください。明示的に その名前を書く必要があります。

MultiViews の効果は以下のようになります: サーバが /some/dir/foo へのリクエストを受け取り、/some/dirMultiViews が有効であって、 /some/dir/foo が存在しない場合、 サーバはディレクトリを読んで foo.* にあてはまる全てのファイルを探し、 事実上それらのファイルをマップするタイプマップを作ります。 そのとき、メディアタイプとコンテントエンコーディングは、そのファイル名を 直接指定したときと同じものが割り当てられます。 それからクライアントの要求に一番合うものを選びます。

サーバがディレクトリの索引を作ろうとしている場合、 MultiViewsDirectoryIndex ディレクティブで指定されたファイルを探す過程にも 適用されます。設定ファイルに

DirectoryIndex index

が書かれていて、index.htmlindex.html3 が 両方存在していると、サーバはその中からどちらかを適当に選びます。 もしその両方が存在せずに index.cgi が存在していると、 サーバはそれを実行します。

もしディレクトリを読んでいる際に、 文字セット、コンテントタイプ、言語、エンコーディングを 指定するための mod_mime で認識できる拡張子を持たないファイルが見つかると、結果は MultiViewsMatch ディレクティブの設定に依存します。このディレクティブは ハンドラ、フィルタ、他のファイル拡張子タイプのどれが MultiViews ネゴシエーションで使用できるかを決定します。

top

ネゴシエーション方法

Apache はリソースの variant の一覧を、タイプマップファイルか ディレクトリ内のファイル名からかで取得した後、 「最適な」 variant を決定するために二つの方法の どちらかを起動します。 Apache のコンテントネゴシエーションの機能を使うために、 どのようにしてこの調停が行われるか詳細を知る必要はありません。 しかしながら、この文書の残りでは関心のある人のために、 使用されている方法について説明しています。

ネゴシエーション方法は二つあります。

  1. 通常は Apache のアルゴリズムを用いた Server driven negotiation が使用されます。Apache のアルゴリズムは後に詳細に説明されています。 このアルゴリズムが使用された場合、Apache はより良い結果になるように、特定の次元において品質の値を 「変える」ことができます。Apache が品質の値を変える方法は後で詳細に説明されています。
  2. RFC 2295 で定義されている機構を用いてブラウザが特に指定した場合、 transparent content negotiation が使用されます。このネゴシエーション方法では、「最適な」 variant の決定をブラウザが完全に制御することができます。 ですから、結果はブラウザが使用しているアルゴリズムに依存します。 Transparent negotiation の処理の過程で、ブラウザは RFC 2296 で 定義されている 'remote variant selection algorithm' を実行するように頼むことができます。

ネゴシエーションの次元

次元 説明
メディアタイプ ブラウザは Accept ヘッダフィールドで優先傾向を指定します。 アイテムそれぞれは、関連した品質数値を持つことができます。 variant の説明も品質数値を持つことができます ("qs" パラメータをご覧下さい)。
言語 ブラウザは Accept-Language ヘッダフィールドで優先傾向を指定します。 要素それぞれに品質数値を持たせることができます。 variants は 0 か 1 つかそれ以上の言語と 関連づけることができます。
エンコーディング ブラウザは Accept-Encoding ヘッダフィールドで優先傾向を指定します。 要素それぞれに品質数値を持たせることができます。
文字セット ブラウザは Accept-Charset ヘッダフィールドで優先傾向を指定します。 要素それぞれに品質数値を持たせることができます。 variant はメディアタイプのパラメータとして文字セットを 指定することもできます。

Apache ネゴシエーションアルゴリズム

ブラウザに返す「最適な」variant を (もしあれば) 選択するように Apache は次のアルゴリズムを使うことができます。 このアルゴリズムを設定により変更することはできません。 次のように動作します:

  1. まずはじめに、ネゴシエーションの次元それぞれについて適切な Accept* ヘッダフィールドを調べ、 variant それぞれに品質を割り当てます。 もしある次元の Accept* ヘッダでその variant が許容できないことが示されていれば、それを削除します。 variant が一つも残っていなければ、ステップ 4 に行きます。
  2. 消去法で「最適な」 variant を選びます。 次のテストが順番に適用されます。 テストで選択されなかった variant は削除されていきます。 テスト後 variant が一つだけ残っていれば、それを最適なものとして ステップ 3 に進みます。 複数 variant が残っていれば、次のテストに進みます。
    1. variant のメディアタイプの品質数値と Accept ヘッダの品質数値との積を計算して、最高値の variant を選びます。
    2. 言語品質数値が最高の variant を選びます。
    3. (もしあれば) Accept-Language ヘッダの言語順か、 (もしあれば) LanguagePriority ディレクティブの言語順で最適な言語の variant を選びます。
    4. 最高「レベル」のメディアパラメータ (text/html メディアタイプのバージョンを与えるために使われます) を持つ variant を選びます。
    5. Accept-Charset ヘッダ行で与えられている最高の文字セット メディアパラメータを持つ variant を選びます。 明示的に除外されていない限り、ISO-8859-1 が許容されるようになっています。 text/* メディアタイプであるけれども 特定の文字セットに明示的に関連づけられているわけではない variant は ISO-8859-1 であると仮定されます。
    6. ISO-8859-1 ではない文字セットメディアパラメータと 関連づけられている variant を選びます。 そのような variant がない場合は、代わりに全ての variant を選びます。
    7. 最適なエンコーディングの variant を選びます。 もし user-agent が許容するエンコーディングがあれば、 その variant のみを選びます。 そうではなく、もしエンコードされたものとそうでない variant が混ざって存在していたらエンコードされていない variant のみを選びます。 variant が全部エンコードされているか variant が全部エンコードされていないという場合は、 全ての variant を選びます。
    8. 内容の最も短い variant を選びます。
    9. 残っている variant の最初のものを選びます。 タイプマップファイルの最初にリストされているか、 variant がディレクトリから最初に読み込まれる時に ASCII順でソートしてファイル名が先頭になったか、のどちらかです。
  3. アルゴリズムを使って一つの「最適な」variant を選びましたので、 それを応答として返します。ネゴシエーションの次元を指定するために HTTP レスポンスヘッダ Vary が設定されます (リソースのキャッシュをする時に、 ブラウザやキャッシュはこの情報を使うことができます)。 以上で終わり。
  4. ここに来たということは、variant が一つも選択されなかった (ブラウザが許容するものがなかったため) ということです。 406 ステータス ("No Acceptable representation" を意味する) が、利用可能な variant のリストのついた HTML ドキュメントとともに返されます。 相違の次元を示す HTTP Vary ヘッダも設定されます。
top

品質の値を変える

上記の Apache ネゴシエーションアルゴリズムの厳格な解釈で 得られるであろう値から、Apache は品質数値を時々変えます。 これは、このアルゴリズムで完全ではない、あるいは正確でない情報を送る ブラウザ向けによりよい結果を得るために行われます。 かなりポピュラーなブラウザで、もしないと間違った variant を選択する結果になってしまうような Accept ヘッダ情報を送るものもあります。 ブラウザが完全で正しい情報を送っていれば、 この数値変化は適用されません。

メディアタイプとワイルドカード

Accept: リクエストヘッダはメディアタイプの優先傾向を指定します。 これはまた、"image/*" や "*/*" といった「ワイルドカード」メディアタイプを含むことができます。 ここで * は任意の文字列にマッチします。 ですから、次の:

Accept: image/*, */*

を含むリクエストは、"image/" ではじまるタイプ全てが許容できる、 そして他のどんなタイプも許容できる (この場合はじめの "image/*" は冗長になります) ことを示します。 扱うことのできる明示的なタイプに加えて、機械的に ワイルドカードを送るブラウザもあります。例えば:

Accept: text/html, text/plain, image/gif, image/jpeg, */*

こうすることの狙いは、明示的にリストしているタイプが優先されるけれども、 異なる表現が利用可能であればそれでも良い、ということです。 しかしながら、上の基本的なアルゴリズムでは、 */* ワイルドカードは他の全てのタイプと全く同等なので優先されません。 ブラウザは */* にもっと低い品質 (優先) 値を付けてリクエストを送るべきなのです。例えば:

Accept: text/html, text/plain, image/gif, image/jpeg, */*; q=0.01

明示的なタイプには品質数値が付けられていませんので、 デフォルトの 1.0 (最高値) の優先になります。 ワイルドカード */* は低い優先度 0.01 を与えられているので、 明示的にリストされているタイプに合致する variant がない場合にのみ、 他のタイプが返されます。

もし Accept: ヘッダが q 値を全く含んでいなければ、 望みの挙動をするために、 Apache は "*/*" があれば 0.01 の q 値を設定します。 また、"type/*" の形のワイルドカードには 0.02 の q 値を設定します (ですからこれらは "*/*" のマッチよりも優先されます)。 もし Accept: ヘッダ中のメディアタイプのどれかが q 値を含んでいれば、これらの特殊な値は適応されず、 正しい情報を送るブラウザからのリクエストは期待通りに 動作するようになります。

言語ネゴシエーションの例外処理

Apache 2.0 では新たに、言語ネゴシエーションが適合するものを 見つけるのに失敗した時に、優雅にフォールバックできるような ネゴシエーションアルゴリズムが幾つか追加されました。

サーバのページをクライアントがリクエストしたけれども、 ブラウザの送ってきた Accept-Language に合致するページが一つも 見つからなかった場合に、サーバは "No Acceptable Variant" か "Multiple Choices" レスポンスをクライアントに返します。 これらのエラーメッセージを返さないように、 このような場合には Apache が Accept-Language を無視して、 クライアントのリクエストに明示的には合致しないドキュメントを 提供するように設定できます。 ForceLanguagePriority ディレクティブは、これらのエラーの一つか両方をオーバーライドするために 使用できて、 LanguagePriority ディレクティブの内容を使ってサーバの判断を代行するようにできます。

サーバは他に適合するものが見つからなければ、 言語サブセットで適合するものを試そうともします。 例えばクライアントが英国英語である en-GB 言語で ドキュメントをリクエストした場合、サーバは HTTP/1.1 規格では、単に en とマークされているドキュメントを マッチするものとすることは通常は許されていません。 (英国英語は理解できるけど一般的な英語は理解できないという読み手は 考えられないので、Accept-Language ヘッダで en-GB を含んで en を含まないのはほぼ確実に設定の間違いである、 ということに注意してください。 ですが不幸なことに、多くのクライアントではデフォルトで このような設定になっています。) しかしながら、他の言語にはマッチせず、"No Acceptable Variants" エラーを返したり、 LanguagePriority にフォールバックしようとしているときは、 サブセット指定を無視して、en-GBen にマッチします。 Apache はクライアントの許容言語リストに暗黙に 非常に低い品質値の親言語を加えることになります。 しかし、クライアントが "en-GB; q=0.9, fr; q=0.8" とリクエストして、 サーバが "en" と "fr" と設計されたドキュメントを持っている場合は、 "fr" ドキュメントが返されることに注意してください。 このような処理は、HTTP 1.1 規格との整合性を維持して、 適切に設定されたクライアントともきちんと動作するために 必要です。

より高度なテクニック (Cookie や特殊な URL パス等) においてもユーザの言語選択をサポートするため、 Apache 2.0.47 からは、mod_negotiation環境変数 prefer-language を認識するようになりました。 この変数が存在して、適切な言語タグが代入されているのであれば、 mod_negotiation は合致する variant を選択しようとします。合致するものが無ければ、 通常のネゴシエーション手順が適用されます。

Example

SetEnvIf Cookie "language=(.+)" prefer-language=$1

top

Transparent Content Negotiation の拡張

Apache は transparent content negotiation プロトコル (RFC 2295) を次のように拡張しています。 特定のコンテントエンコーディングのみが利用可能である variant に印を付けるために、新たに {encoding ..} 要素を variant リスト中に使っています。 リスト中のエンコードされた variant を認識し、 Accept-Encoding リクエストヘッダに従って許容される エンコードをもった variant は、どれでも候補 variant として使用するように、 RVSA/1.0 アルゴリズム (RFC 2296) の実装が拡張されました。 RVSA/1.0 の実装では、最適な variant が見つかるまで、 計算した品質数値は小数点以下 5 桁まで丸めません。

top

リンクと名前の変換に関する注意点

言語ネゴシエーションを使っている場合は、 ファイルが一つ以上の拡張子を持てて、 拡張子の順番は通常は考慮されない (詳細は mod_mime を参照) ので、 幾つかの異なる名前の変換を選べることになります。

典型的なファイルでは、MIME タイプ拡張子 (例えば html) を持っていて、エンコーディング拡張子 (例えば gz) を持っているかもしれなくて、 このファイルに異なる言語 variant を用意していれば、 もちろん言語拡張子 (例えば en) を持っているでしょう。

例:

ファイル名と、それに対して使えるリンクと使えないリンクの例です:

ファイル名 使えるリンク 使えないリンク
foo.html.en foo
foo.html
-
foo.en.html foo foo.html
foo.html.en.gz foo
foo.html
foo.gz
foo.html.gz
foo.en.html.gz foo foo.html
foo.html.gz
foo.gz
foo.gz.html.en foo
foo.gz
foo.gz.html
foo.html
foo.html.gz.en foo
foo.html
foo.html.gz
foo.gz

上の表を見て、拡張子なしのリンク (例えば foo) がいつでも使えることに気が付くでしょう。 この利点は、ドキュメントとして応答するファイルの 実際のファイルタイプを隠蔽して、リンクの参照を変更することなく 後からファイルを変更できる、 例えば html から shtml に、あるいは cgi に変更できる点です。

リンクに MIME タイプを使い続けたい (例えば foo.html)時は、言語拡張子は (エンコーディング拡張子もあればそれも含めて) MIME タイプ拡張子の右側になければなりません (例えば foo.html.en)。

top

キャッシュに関する注意事項

キャッシュが一つの表現を保存しているときは、 リクエスト URL と関連づけられています。 次にその URL がリクエストされた時に、キャッシュは 保存されている表現を使用できます。しかし、 リソースがサーバでネゴシエーション可能であれば、 最初のリクエストでキャッシュされて続くキャッシュヒットでは 間違った応答を返してしまうということになりかねません。 これを防ぐために、Apache はコンテントネゴシエーションの 後に返された応答全てに、HTTP/1.0 クライアントでは キャッシュ不可能の印をつけます。 また、ネゴシエーションされた応答のキャッシュを可能にする HTTP/1.1 プロトコルの機能も Apache はサポートします。

HTTP/1.0 準拠のクライアントからのリクエストに対しては、 (ブラウザであろうとキャッシュであろうと) ネゴシエーションを受けた応答のキャッシュを許すために、 CacheNegotiatedDocs ディレクティブを使用できます。 このディレクティブは、サーバ設定ファイルやバーチャルホストに書くことができ、 引数をとりません。 HTTP/1.1 クライアントからのリクエストには効力を持ちません。

HTTP/1.1 クライアントに対しては、レスポンスのネゴシエーション次元 を示すために Vary HTTP レスポンスヘッダを送ります。 キャッシュは、これを使って後続のリクエストに対してローカルコピーで応答できるか どうかを決定できます。 ネゴシエーション次元とは関係なしにローカルコピーの使用を優先するようにするには、 force-no-vary 環境変数を 設定します。

top

追加情報

コンテントネゴシエーションに関する追加情報は、 Alan J. Flavell さんのLanguage Negotiation Notes をご覧下さい。ですが、 Apache 2.0 での変更点を含むためには更新されていないかもしれない ということに注意してください。

custom-error.html100644 0 0 20134 10422374001 11545 0ustar 0 0 カスタムエラーレスポンス - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

カスタムエラーレスポンス

ウェブマスターが何らかのエラーや問題に対する Apache の反応を設定できるようにする追加機能を提供します。

サーバがエラーや問題を発見した場合の反応を、 カスタマイズして定義することができます。

スクリプトの実行が失敗して "500 Server Error" を発生させたとします。この場合の反応を、より好ましいテキストや、別の URL (内部及び外部) へのリダイレクションに置き換えることができます。

top

動作

古い動作

NCSA httpd 1.3 は、古くて退屈なエラー/問題メッセージを 返していました。それはしばしばユーザには無意味であり、 またそれを発生させた原因を記録する方法も提供していませんでした。

新しい動作

  1. NCSA のハードコードされたメッセージの代わりに 他のテキストを表示
  2. ローカルの URL にリダイレクト
  3. 外部の URL にリダイレクト

するようにサーバを設定できます。

別の URL にリダイレクトすることは役に立ちますが、 それは説明をしたり、より明確に誤り/問題を記録したりするために 何か情報を伝えられるときに限ります。

これを実現するために、 Apache は新しく CGI のような環境変数を 定義します:

REDIRECT_HTTP_ACCEPT=*/*, image/gif, image/x-xbitmap, image/jpeg
REDIRECT_HTTP_USER_AGENT=Mozilla/1.1b2 (X11; I; HP-UX A.09.05 9000/712)
REDIRECT_PATH=.:/bin:/usr/local/bin:/etc
REDIRECT_QUERY_STRING=
REDIRECT_REMOTE_ADDR=121.345.78.123
REDIRECT_REMOTE_HOST=ooh.ahhh.com
REDIRECT_SERVER_NAME=crash.bang.edu
REDIRECT_SERVER_PORT=80
REDIRECT_SERVER_SOFTWARE=Apache/0.8.15
REDIRECT_URL=/cgi-bin/buggy.pl

頭に付く REDIRECT_ に注目してください。

少なくとも REDIRECT_URLREDIRECT_QUERY_STRING は新しい URL (CGI スクリプトか CGI インクルードであると仮定されます) に渡されます。 他の変数は、エラーや問題が起きる前に存在した場合にだけ存在します。 もしあなたの設定した ErrorDocument外部リダイレクト (すなわちhttp: のような体系名から始まるすべてのもの。たとえ同じホストを指していても) ならば、これらはまったく設定されません。

top

設定

AllowOverride が適切に設定されていれば、 .htaccess ファイルで ErrorDocument を使用することができます。

ここに、いくつかの例を挙げます。

ErrorDocument 500 /cgi-bin/crash-recover
ErrorDocument 500 "Sorry, our script crashed. Oh dear"
ErrorDocument 500 http://xxx/
ErrorDocument 404 /Lame_excuses/not_found.html
ErrorDocument 401 /Subscription/how_to_subscribe.html

構文

ErrorDocument <3-digit-code> <action>

action (動作) は、

  1. 表示されるべきテキスト。テキストには引用符 (") をつけます。 引用符の後に続くものが何でも表示されます。 注意 : (") は表示されません
  2. リダイレクト先の外部 URL
  3. リダイレクト先のローカル URL
top

カスタムエラーレスポンスとリダイレクト

スクリプト/SSI に追加の環境変数が利用可能になるように、 リダイレクトされた URL に対する Apache の動作が変更されました。

古い動作

リダイレクトされたスクリプトは標準の CGI 環境変数を利用可能でした。しかし、どこからリダイレクト されたかの情報は提供されていませんでした。

新しい動作

リダイレクトされた先のスクリプトが使用可能なように、 新しいたくさんの環境変数が初期化されます。新しい変数は、それぞれ REDIRECT_ で始まります。 REDIRECT_ で始まる環境変数はリダイレクトされる前に存在していた CGI 環境変数の頭に REDIRECT_ を付けて作成されます。 すなわちHTTP_USER_AGENTREDIRECT_HTTP_USER_AGENT になります。 これらの新しい変数に加えて、Apache は、 スクリプトがリダイレクト元のトレースを助けるために REDIRECT_URLREDIRECT_STATUS を定義します。アクセスログには元の URL とリダイレクトされた URL の両方が記録されます。

ErrorDocument が CGI スクリプトへのローカルリダイレクトを 指定している場合は、それを起動することになったエラーの状態を クライアントまで確実に伝えるために "Status:" ヘッダを含むべきです。例えば、ErrorDocument 用の Perl スクリプトは以下のようなものを含むかもしれません。

...
print "Content-type: text/html\n";
printf "Status: %s Condition Intercepted\n", $ENV{"REDIRECT_STATUS"};
...

スクリプトが 404 Not Found のような 特定のエラーコンディションを扱うためだけに使われる場合は、 代わりに特定のコードとエラーテキストを使用することができます。

developer/API.html100644 0 0 172355 10422374001 11537 0ustar 0 0 Apache 1.3 API notes - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > Developer Documentation

Apache 1.3 API notes

Warning

This document has not been updated to take into account changes made in the 2.0 version of the Apache HTTP Server. Some of the information may still be relevant, but please use it with care.

These are some notes on the Apache API and the data structures you have to deal with, etc. They are not yet nearly complete, but hopefully, they will help you get your bearings. Keep in mind that the API is still subject to change as we gain experience with it. (See the TODO file for what might be coming). However, it will be easy to adapt modules to any changes that are made. (We have more modules to adapt than you do).

A few notes on general pedagogical style here. In the interest of conciseness, all structure declarations here are incomplete -- the real ones have more slots that I'm not telling you about. For the most part, these are reserved to one component of the server core or another, and should be altered by modules with caution. However, in some cases, they really are things I just haven't gotten around to yet. Welcome to the bleeding edge.

Finally, here's an outline, to give you some bare idea of what's coming up, and in what order:

top

Basic concepts

We begin with an overview of the basic concepts behind the API, and how they are manifested in the code.

Handlers, Modules, and Requests

Apache breaks down request handling into a series of steps, more or less the same way the Netscape server API does (although this API has a few more stages than NetSite does, as hooks for stuff I thought might be useful in the future). These are:

These phases are handled by looking at each of a succession of modules, looking to see if each of them has a handler for the phase, and attempting invoking it if so. The handler can typically do one of three things:

Most phases are terminated by the first module that handles them; however, for logging, `fixups', and non-access authentication checking, all handlers always run (barring an error). Also, the response phase is unique in that modules may declare multiple handlers for it, via a dispatch table keyed on the MIME type of the requested object. Modules may declare a response-phase handler which can handle any request, by giving it the key */* (i.e., a wildcard MIME type specification). However, wildcard handlers are only invoked if the server has already tried and failed to find a more specific response handler for the MIME type of the requested object (either none existed, or they all declined).

The handlers themselves are functions of one argument (a request_rec structure. vide infra), which returns an integer, as above.

A brief tour of a module

At this point, we need to explain the structure of a module. Our candidate will be one of the messier ones, the CGI module -- this handles both CGI scripts and the ScriptAlias config file command. It's actually a great deal more complicated than most modules, but if we're going to have only one example, it might as well be the one with its fingers in every place.

Let's begin with handlers. In order to handle the CGI scripts, the module declares a response handler for them. Because of ScriptAlias, it also has handlers for the name translation phase (to recognize ScriptAliased URIs), the type-checking phase (any ScriptAliased request is typed as a CGI script).

The module needs to maintain some per (virtual) server information, namely, the ScriptAliases in effect; the module structure therefore contains pointers to a functions which builds these structures, and to another which combines two of them (in case the main server and a virtual server both have ScriptAliases declared).

Finally, this module contains code to handle the ScriptAlias command itself. This particular module only declares one command, but there could be more, so modules have command tables which declare their commands, and describe where they are permitted, and how they are to be invoked.

A final note on the declared types of the arguments of some of these commands: a pool is a pointer to a resource pool structure; these are used by the server to keep track of the memory which has been allocated, files opened, etc., either to service a particular request, or to handle the process of configuring itself. That way, when the request is over (or, for the configuration pool, when the server is restarting), the memory can be freed, and the files closed, en masse, without anyone having to write explicit code to track them all down and dispose of them. Also, a cmd_parms structure contains various information about the config file being read, and other status information, which is sometimes of use to the function which processes a config-file command (such as ScriptAlias). With no further ado, the module itself:

/* Declarations of handlers. */

int translate_scriptalias (request_rec *);
int type_scriptalias (request_rec *);
int cgi_handler (request_rec *);

/* Subsidiary dispatch table for response-phase
 * handlers, by MIME type */

handler_rec cgi_handlers[] = {
{ "application/x-httpd-cgi", cgi_handler },
{ NULL }
};

/* Declarations of routines to manipulate the
 * module's configuration info. Note that these are
 * returned, and passed in, as void *'s; the server
 * core keeps track of them, but it doesn't, and can't,
 * know their internal structure.
 */

void *make_cgi_server_config (pool *);
void *merge_cgi_server_config (pool *, void *, void *);

/* Declarations of routines to handle config-file commands */

extern char *script_alias(cmd_parms *, void *per_dir_config, char *fake, char *real);

command_rec cgi_cmds[] = {
{ "ScriptAlias", script_alias, NULL, RSRC_CONF, TAKE2,
"a fakename and a realname"},
{ NULL }
};

module cgi_module = {

  STANDARD_MODULE_STUFF,
  NULL,                     /* initializer */
  NULL,                     /* dir config creator */
  NULL,                     /* dir merger */
  make_cgi_server_config,   /* server config */
  merge_cgi_server_config,  /* merge server config */
  cgi_cmds,                 /* command table */
  cgi_handlers,             /* handlers */
  translate_scriptalias,    /* filename translation */
  NULL,                     /* check_user_id */
  NULL,                     /* check auth */
  NULL,                     /* check access */
  type_scriptalias,         /* type_checker */
  NULL,                     /* fixups */
  NULL,                     /* logger */
  NULL                      /* header parser */
};
top

How handlers work

The sole argument to handlers is a request_rec structure. This structure describes a particular request which has been made to the server, on behalf of a client. In most cases, each connection to the client generates only one request_rec structure.

A brief tour of the request_rec

The request_rec contains pointers to a resource pool which will be cleared when the server is finished handling the request; to structures containing per-server and per-connection information, and most importantly, information on the request itself.

The most important such information is a small set of character strings describing attributes of the object being requested, including its URI, filename, content-type and content-encoding (these being filled in by the translation and type-check handlers which handle the request, respectively).

Other commonly used data items are tables giving the MIME headers on the client's original request, MIME headers to be sent back with the response (which modules can add to at will), and environment variables for any subprocesses which are spawned off in the course of servicing the request. These tables are manipulated using the ap_table_get and ap_table_set routines.

Note that the Content-type header value cannot be set by module content-handlers using the ap_table_*() routines. Rather, it is set by pointing the content_type field in the request_rec structure to an appropriate string. e.g.,

r->content_type = "text/html";

Finally, there are pointers to two data structures which, in turn, point to per-module configuration structures. Specifically, these hold pointers to the data structures which the module has built to describe the way it has been configured to operate in a given directory (via .htaccess files or <Directory> sections), for private data it has built in the course of servicing the request (so modules' handlers for one phase can pass `notes' to their handlers for other phases). There is another such configuration vector in the server_rec data structure pointed to by the request_rec, which contains per (virtual) server configuration data.

Here is an abridged declaration, giving the fields most commonly used:

struct request_rec {

pool *pool;
conn_rec *connection;
server_rec *server;

/* What object is being requested */

char *uri;
char *filename;
char *path_info;

char *args;           /* QUERY_ARGS, if any */
struct stat finfo;    /* Set by server core;
                       * st_mode set to zero if no such file */

char *content_type;
char *content_encoding;

/* MIME header environments, in and out. Also,
 * an array containing environment variables to
 * be passed to subprocesses, so people can write
 * modules to add to that environment.
 *
 * The difference between headers_out and
 * err_headers_out is that the latter are printed
 * even on error, and persist across internal
 * redirects (so the headers printed for
 * ErrorDocument handlers will have them).
 */

table *headers_in;
table *headers_out;
table *err_headers_out;
table *subprocess_env;

/* Info about the request itself... */

int header_only;     /* HEAD request, as opposed to GET */
char *protocol;      /* Protocol, as given to us, or HTTP/0.9 */
char *method;        /* GET, HEAD, POST, etc. */
int method_number;   /* M_GET, M_POST, etc. */

/* Info for logging */

char *the_request;
int bytes_sent;

/* A flag which modules can set, to indicate that
 * the data being returned is volatile, and clients
 * should be told not to cache it.
 */

int no_cache;

/* Various other config info which may change
 * with .htaccess files
 * These are config vectors, with one void*
 * pointer for each module (the thing pointed
 * to being the module's business).
 */

void *per_dir_config;   /* Options set in config files, etc. */
void *request_config;   /* Notes on *this* request */


};

Where request_rec structures come from

Most request_rec structures are built by reading an HTTP request from a client, and filling in the fields. However, there are a few exceptions:

Handling requests, declining, and returning error codes

As discussed above, each handler, when invoked to handle a particular request_rec, has to return an int to indicate what happened. That can either be

Note that if the error code returned is REDIRECT, then the module should put a Location in the request's headers_out, to indicate where the client should be redirected to.

Special considerations for response handlers

Handlers for most phases do their work by simply setting a few fields in the request_rec structure (or, in the case of access checkers, simply by returning the correct error code). However, response handlers have to actually send a request back to the client.

They should begin by sending an HTTP response header, using the function ap_send_http_header. (You don't have to do anything special to skip sending the header for HTTP/0.9 requests; the function figures out on its own that it shouldn't do anything). If the request is marked header_only, that's all they should do; they should return after that, without attempting any further output.

Otherwise, they should produce a request body which responds to the client as appropriate. The primitives for this are ap_rputc and ap_rprintf, for internally generated output, and ap_send_fd, to copy the contents of some FILE * straight to the client.

At this point, you should more or less understand the following piece of code, which is the handler which handles GET requests which have no more specific handler; it also shows how conditional GETs can be handled, if it's desirable to do so in a particular response handler -- ap_set_last_modified checks against the If-modified-since value supplied by the client, if any, and returns an appropriate code (which will, if nonzero, be USE_LOCAL_COPY). No similar considerations apply for ap_set_content_length, but it returns an error code for symmetry.

int default_handler (request_rec *r)
{
int errstatus;
FILE *f;

if (r->method_number != M_GET) return DECLINED;
if (r->finfo.st_mode == 0) return NOT_FOUND;

if ((errstatus = ap_set_content_length (r, r->finfo.st_size))
    || (errstatus = ap_set_last_modified (r, r->finfo.st_mtime)))
return errstatus;

f = fopen (r->filename, "r");

if (f == NULL) {
log_reason("file permissions deny server access", r->filename, r);
return FORBIDDEN;
}

register_timeout ("send", r);
ap_send_http_header (r);

if (!r->header_only) send_fd (f, r);
ap_pfclose (r->pool, f);
return OK;
}

Finally, if all of this is too much of a challenge, there are a few ways out of it. First off, as shown above, a response handler which has not yet produced any output can simply return an error code, in which case the server will automatically produce an error response. Secondly, it can punt to some other handler by invoking ap_internal_redirect, which is how the internal redirection machinery discussed above is invoked. A response handler which has internally redirected should always return OK.

(Invoking ap_internal_redirect from handlers which are not response handlers will lead to serious confusion).

Special considerations for authentication handlers

Stuff that should be discussed here in detail:

Special considerations for logging handlers

When a request has internally redirected, there is the question of what to log. Apache handles this by bundling the entire chain of redirects into a list of request_rec structures which are threaded through the r->prev and r->next pointers. The request_rec which is passed to the logging handlers in such cases is the one which was originally built for the initial request from the client; note that the bytes_sent field will only be correct in the last request in the chain (the one for which a response was actually sent).

top

Resource allocation and resource pools

One of the problems of writing and designing a server-pool server is that of preventing leakage, that is, allocating resources (memory, open files, etc.), without subsequently releasing them. The resource pool machinery is designed to make it easy to prevent this from happening, by allowing resource to be allocated in such a way that they are automatically released when the server is done with them.

The way this works is as follows: the memory which is allocated, file opened, etc., to deal with a particular request are tied to a resource pool which is allocated for the request. The pool is a data structure which itself tracks the resources in question.

When the request has been processed, the pool is cleared. At that point, all the memory associated with it is released for reuse, all files associated with it are closed, and any other clean-up functions which are associated with the pool are run. When this is over, we can be confident that all the resource tied to the pool have been released, and that none of them have leaked.

Server restarts, and allocation of memory and resources for per-server configuration, are handled in a similar way. There is a configuration pool, which keeps track of resources which were allocated while reading the server configuration files, and handling the commands therein (for instance, the memory that was allocated for per-server module configuration, log files and other files that were opened, and so forth). When the server restarts, and has to reread the configuration files, the configuration pool is cleared, and so the memory and file descriptors which were taken up by reading them the last time are made available for reuse.

It should be noted that use of the pool machinery isn't generally obligatory, except for situations like logging handlers, where you really need to register cleanups to make sure that the log file gets closed when the server restarts (this is most easily done by using the function ap_pfopen, which also arranges for the underlying file descriptor to be closed before any child processes, such as for CGI scripts, are execed), or in case you are using the timeout machinery (which isn't yet even documented here). However, there are two benefits to using it: resources allocated to a pool never leak (even if you allocate a scratch string, and just forget about it); also, for memory allocation, ap_palloc is generally faster than malloc.

We begin here by describing how memory is allocated to pools, and then discuss how other resources are tracked by the resource pool machinery.

Allocation of memory in pools

Memory is allocated to pools by calling the function ap_palloc, which takes two arguments, one being a pointer to a resource pool structure, and the other being the amount of memory to allocate (in chars). Within handlers for handling requests, the most common way of getting a resource pool structure is by looking at the pool slot of the relevant request_rec; hence the repeated appearance of the following idiom in module code:

int my_handler(request_rec *r)
{
struct my_structure *foo;
...

foo = (foo *)ap_palloc (r->pool, sizeof(my_structure));
}

Note that there is no ap_pfree -- ap_palloced memory is freed only when the associated resource pool is cleared. This means that ap_palloc does not have to do as much accounting as malloc(); all it does in the typical case is to round up the size, bump a pointer, and do a range check.

(It also raises the possibility that heavy use of ap_palloc could cause a server process to grow excessively large. There are two ways to deal with this, which are dealt with below; briefly, you can use malloc, and try to be sure that all of the memory gets explicitly freed, or you can allocate a sub-pool of the main pool, allocate your memory in the sub-pool, and clear it out periodically. The latter technique is discussed in the section on sub-pools below, and is used in the directory-indexing code, in order to avoid excessive storage allocation when listing directories with thousands of files).

Allocating initialized memory

There are functions which allocate initialized memory, and are frequently useful. The function ap_pcalloc has the same interface as ap_palloc, but clears out the memory it allocates before it returns it. The function ap_pstrdup takes a resource pool and a char * as arguments, and allocates memory for a copy of the string the pointer points to, returning a pointer to the copy. Finally ap_pstrcat is a varargs-style function, which takes a pointer to a resource pool, and at least two char * arguments, the last of which must be NULL. It allocates enough memory to fit copies of each of the strings, as a unit; for instance:

ap_pstrcat (r->pool, "foo", "/", "bar", NULL);

returns a pointer to 8 bytes worth of memory, initialized to "foo/bar".

Commonly-used pools in the Apache Web server

A pool is really defined by its lifetime more than anything else. There are some static pools in http_main which are passed to various non-http_main functions as arguments at opportune times. Here they are:

permanent_pool
never passed to anything else, this is the ancestor of all pools
pconf
  • subpool of permanent_pool
  • created at the beginning of a config "cycle"; exists until the server is terminated or restarts; passed to all config-time routines, either via cmd->pool, or as the "pool *p" argument on those which don't take pools
  • passed to the module init() functions
ptemp
  • sorry I lie, this pool isn't called this currently in 1.3, I renamed it this in my pthreads development. I'm referring to the use of ptrans in the parent... contrast this with the later definition of ptrans in the child.
  • subpool of permanent_pool
  • created at the beginning of a config "cycle"; exists until the end of config parsing; passed to config-time routines via cmd->temp_pool. Somewhat of a "bastard child" because it isn't available everywhere. Used for temporary scratch space which may be needed by some config routines but which is deleted at the end of config.
pchild
  • subpool of permanent_pool
  • created when a child is spawned (or a thread is created); lives until that child (thread) is destroyed
  • passed to the module child_init functions
  • destruction happens right after the child_exit functions are called... (which may explain why I think child_exit is redundant and unneeded)
ptrans
  • should be a subpool of pchild, but currently is a subpool of permanent_pool, see above
  • cleared by the child before going into the accept() loop to receive a connection
  • used as connection->pool
r->pool
  • for the main request this is a subpool of connection->pool; for subrequests it is a subpool of the parent request's pool.
  • exists until the end of the request (i.e., ap_destroy_sub_req, or in child_main after process_request has finished)
  • note that r itself is allocated from r->pool; i.e., r->pool is first created and then r is the first thing palloc()d from it

For almost everything folks do, r->pool is the pool to use. But you can see how other lifetimes, such as pchild, are useful to some modules... such as modules that need to open a database connection once per child, and wish to clean it up when the child dies.

You can also see how some bugs have manifested themself, such as setting connection->user to a value from r->pool -- in this case connection exists for the lifetime of ptrans, which is longer than r->pool (especially if r->pool is a subrequest!). So the correct thing to do is to allocate from connection->pool.

And there was another interesting bug in mod_include / mod_cgi. You'll see in those that they do this test to decide if they should use r->pool or r->main->pool. In this case the resource that they are registering for cleanup is a child process. If it were registered in r->pool, then the code would wait() for the child when the subrequest finishes. With mod_include this could be any old #include, and the delay can be up to 3 seconds... and happened quite frequently. Instead the subprocess is registered in r->main->pool which causes it to be cleaned up when the entire request is done -- i.e., after the output has been sent to the client and logging has happened.

Tracking open files, etc.

As indicated above, resource pools are also used to track other sorts of resources besides memory. The most common are open files. The routine which is typically used for this is ap_pfopen, which takes a resource pool and two strings as arguments; the strings are the same as the typical arguments to fopen, e.g.,

...
FILE *f = ap_pfopen (r->pool, r->filename, "r");

if (f == NULL) { ... } else { ... }

There is also a ap_popenf routine, which parallels the lower-level open system call. Both of these routines arrange for the file to be closed when the resource pool in question is cleared.

Unlike the case for memory, there are functions to close files allocated with ap_pfopen, and ap_popenf, namely ap_pfclose and ap_pclosef. (This is because, on many systems, the number of files which a single process can have open is quite limited). It is important to use these functions to close files allocated with ap_pfopen and ap_popenf, since to do otherwise could cause fatal errors on systems such as Linux, which react badly if the same FILE* is closed more than once.

(Using the close functions is not mandatory, since the file will eventually be closed regardless, but you should consider it in cases where your module is opening, or could open, a lot of files).

Other sorts of resources -- cleanup functions

More text goes here. Describe the the cleanup primitives in terms of which the file stuff is implemented; also, spawn_process.

Pool cleanups live until clear_pool() is called: clear_pool(a) recursively calls destroy_pool() on all subpools of a; then calls all the cleanups for a; then releases all the memory for a. destroy_pool(a) calls clear_pool(a) and then releases the pool structure itself. i.e., clear_pool(a) doesn't delete a, it just frees up all the resources and you can start using it again immediately.

Fine control -- creating and dealing with sub-pools, with a note on sub-requests

On rare occasions, too-free use of ap_palloc() and the associated primitives may result in undesirably profligate resource allocation. You can deal with such a case by creating a sub-pool, allocating within the sub-pool rather than the main pool, and clearing or destroying the sub-pool, which releases the resources which were associated with it. (This really is a rare situation; the only case in which it comes up in the standard module set is in case of listing directories, and then only with very large directories. Unnecessary use of the primitives discussed here can hair up your code quite a bit, with very little gain).

The primitive for creating a sub-pool is ap_make_sub_pool, which takes another pool (the parent pool) as an argument. When the main pool is cleared, the sub-pool will be destroyed. The sub-pool may also be cleared or destroyed at any time, by calling the functions ap_clear_pool and ap_destroy_pool, respectively. (The difference is that ap_clear_pool frees resources associated with the pool, while ap_destroy_pool also deallocates the pool itself. In the former case, you can allocate new resources within the pool, and clear it again, and so forth; in the latter case, it is simply gone).

One final note -- sub-requests have their own resource pools, which are sub-pools of the resource pool for the main request. The polite way to reclaim the resources associated with a sub request which you have allocated (using the ap_sub_req_... functions) is ap_destroy_sub_req, which frees the resource pool. Before calling this function, be sure to copy anything that you care about which might be allocated in the sub-request's resource pool into someplace a little less volatile (for instance, the filename in its request_rec structure).

(Again, under most circumstances, you shouldn't feel obliged to call this function; only 2K of memory or so are allocated for a typical sub request, and it will be freed anyway when the main request pool is cleared. It is only when you are allocating many, many sub-requests for a single main request that you should seriously consider the ap_destroy_... functions).

top

Configuration, commands and the like

One of the design goals for this server was to maintain external compatibility with the NCSA 1.3 server --- that is, to read the same configuration files, to process all the directives therein correctly, and in general to be a drop-in replacement for NCSA. On the other hand, another design goal was to move as much of the server's functionality into modules which have as little as possible to do with the monolithic server core. The only way to reconcile these goals is to move the handling of most commands from the central server into the modules.

However, just giving the modules command tables is not enough to divorce them completely from the server core. The server has to remember the commands in order to act on them later. That involves maintaining data which is private to the modules, and which can be either per-server, or per-directory. Most things are per-directory, including in particular access control and authorization information, but also information on how to determine file types from suffixes, which can be modified by AddType and DefaultType directives, and so forth. In general, the governing philosophy is that anything which can be made configurable by directory should be; per-server information is generally used in the standard set of modules for information like Aliases and Redirects which come into play before the request is tied to a particular place in the underlying file system.

Another requirement for emulating the NCSA server is being able to handle the per-directory configuration files, generally called .htaccess files, though even in the NCSA server they can contain directives which have nothing at all to do with access control. Accordingly, after URI -> filename translation, but before performing any other phase, the server walks down the directory hierarchy of the underlying filesystem, following the translated pathname, to read any .htaccess files which might be present. The information which is read in then has to be merged with the applicable information from the server's own config files (either from the <Directory> sections in access.conf, or from defaults in srm.conf, which actually behaves for most purposes almost exactly like <Directory />).

Finally, after having served a request which involved reading .htaccess files, we need to discard the storage allocated for handling them. That is solved the same way it is solved wherever else similar problems come up, by tying those structures to the per-transaction resource pool.

Per-directory configuration structures

Let's look out how all of this plays out in mod_mime.c, which defines the file typing handler which emulates the NCSA server's behavior of determining file types from suffixes. What we'll be looking at, here, is the code which implements the AddType and AddEncoding commands. These commands can appear in .htaccess files, so they must be handled in the module's private per-directory data, which in fact, consists of two separate tables for MIME types and encoding information, and is declared as follows:

typedef struct {
    table *forced_types;      /* Additional AddTyped stuff */
    table *encoding_types;    /* Added with AddEncoding... */
} mime_dir_config;

When the server is reading a configuration file, or <Directory> section, which includes one of the MIME module's commands, it needs to create a mime_dir_config structure, so those commands have something to act on. It does this by invoking the function it finds in the module's `create per-dir config slot', with two arguments: the name of the directory to which this configuration information applies (or NULL for srm.conf), and a pointer to a resource pool in which the allocation should happen.

(If we are reading a .htaccess file, that resource pool is the per-request resource pool for the request; otherwise it is a resource pool which is used for configuration data, and cleared on restarts. Either way, it is important for the structure being created to vanish when the pool is cleared, by registering a cleanup on the pool if necessary).

For the MIME module, the per-dir config creation function just ap_pallocs the structure above, and a creates a couple of tables to fill it. That looks like this:

void *create_mime_dir_config (pool *p, char *dummy)
{
mime_dir_config *new =
(mime_dir_config *) ap_palloc (p, sizeof(mime_dir_config));

new->forced_types = ap_make_table (p, 4);
new->encoding_types = ap_make_table (p, 4);

return new;
}

Now, suppose we've just read in a .htaccess file. We already have the per-directory configuration structure for the next directory up in the hierarchy. If the .htaccess file we just read in didn't have any AddType or AddEncoding commands, its per-directory config structure for the MIME module is still valid, and we can just use it. Otherwise, we need to merge the two structures somehow.

To do that, the server invokes the module's per-directory config merge function, if one is present. That function takes three arguments: the two structures being merged, and a resource pool in which to allocate the result. For the MIME module, all that needs to be done is overlay the tables from the new per-directory config structure with those from the parent:

void *merge_mime_dir_configs (pool *p, void *parent_dirv, void *subdirv)
{
mime_dir_config *parent_dir = (mime_dir_config *)parent_dirv;
mime_dir_config *subdir = (mime_dir_config *)subdirv;
mime_dir_config *new =
(mime_dir_config *)ap_palloc (p, sizeof(mime_dir_config));

new->forced_types = ap_overlay_tables (p, subdir->forced_types,
parent_dir->forced_types);
new->encoding_types = ap_overlay_tables (p, subdir->encoding_types,
parent_dir->encoding_types);

return new;
}

As a note -- if there is no per-directory merge function present, the server will just use the subdirectory's configuration info, and ignore the parent's. For some modules, that works just fine (e.g., for the includes module, whose per-directory configuration information consists solely of the state of the XBITHACK), and for those modules, you can just not declare one, and leave the corresponding structure slot in the module itself NULL.

Command handling

Now that we have these structures, we need to be able to figure out how to fill them. That involves processing the actual AddType and AddEncoding commands. To find commands, the server looks in the module's command table. That table contains information on how many arguments the commands take, and in what formats, where it is permitted, and so forth. That information is sufficient to allow the server to invoke most command-handling functions with pre-parsed arguments. Without further ado, let's look at the AddType command handler, which looks like this (the AddEncoding command looks basically the same, and won't be shown here):

char *add_type(cmd_parms *cmd, mime_dir_config *m, char *ct, char *ext)
{
if (*ext == '.') ++ext;
ap_table_set (m->forced_types, ext, ct);
return NULL;
}

This command handler is unusually simple. As you can see, it takes four arguments, two of which are pre-parsed arguments, the third being the per-directory configuration structure for the module in question, and the fourth being a pointer to a cmd_parms structure. That structure contains a bunch of arguments which are frequently of use to some, but not all, commands, including a resource pool (from which memory can be allocated, and to which cleanups should be tied), and the (virtual) server being configured, from which the module's per-server configuration data can be obtained if required.

Another way in which this particular command handler is unusually simple is that there are no error conditions which it can encounter. If there were, it could return an error message instead of NULL; this causes an error to be printed out on the server's stderr, followed by a quick exit, if it is in the main config files; for a .htaccess file, the syntax error is logged in the server error log (along with an indication of where it came from), and the request is bounced with a server error response (HTTP error status, code 500).

The MIME module's command table has entries for these commands, which look like this:

command_rec mime_cmds[] = {
{ "AddType", add_type, NULL, OR_FILEINFO, TAKE2,
"a mime type followed by a file extension" },
{ "AddEncoding", add_encoding, NULL, OR_FILEINFO, TAKE2,
"an encoding (e.g., gzip), followed by a file extension" },
{ NULL }
};

The entries in these tables are:

Finally, having set this all up, we have to use it. This is ultimately done in the module's handlers, specifically for its file-typing handler, which looks more or less like this; note that the per-directory configuration structure is extracted from the request_rec's per-directory configuration vector by using the ap_get_module_config function.

int find_ct(request_rec *r)
{
int i;
char *fn = ap_pstrdup (r->pool, r->filename);
mime_dir_config *conf = (mime_dir_config *)
ap_get_module_config(r->per_dir_config, &mime_module);
char *type;

if (S_ISDIR(r->finfo.st_mode)) {
r->content_type = DIR_MAGIC_TYPE;
return OK;
}

if((i=ap_rind(fn,'.')) < 0) return DECLINED;
++i;

if ((type = ap_table_get (conf->encoding_types, &fn[i])))
{
r->content_encoding = type;

/* go back to previous extension to try to use it as a type */
fn[i-1] = '\0';
if((i=ap_rind(fn,'.')) < 0) return OK;
++i;
}

if ((type = ap_table_get (conf->forced_types, &fn[i])))
{
r->content_type = type;
}

return OK;
}

Side notes -- per-server configuration, virtual servers, etc.

The basic ideas behind per-server module configuration are basically the same as those for per-directory configuration; there is a creation function and a merge function, the latter being invoked where a virtual server has partially overridden the base server configuration, and a combined structure must be computed. (As with per-directory configuration, the default if no merge function is specified, and a module is configured in some virtual server, is that the base configuration is simply ignored).

The only substantial difference is that when a command needs to configure the per-server private module data, it needs to go to the cmd_parms data to get at it. Here's an example, from the alias module, which also indicates how a syntax error can be returned (note that the per-directory configuration argument to the command handler is declared as a dummy, since the module doesn't actually have per-directory config data):

char *add_redirect(cmd_parms *cmd, void *dummy, char *f, char *url)
{
server_rec *s = cmd->server;
alias_server_conf *conf = (alias_server_conf *)
ap_get_module_config(s->module_config,&alias_module);
alias_entry *new = ap_push_array (conf->redirects);

if (!ap_is_url (url)) return "Redirect to non-URL";

new->fake = f; new->real = url;
return NULL;
}

developer/debugging.html100644 0 0 21627 10422374001 13034 0ustar 0 0 Debugging Memory Allocation in APR - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > Developer Documentation

Debugging Memory Allocation in APR

The allocation mechanisms within APR have a number of debugging modes that can be used to assist in finding memory problems. This document describes the modes available and gives instructions on activating them.

top

Available debugging options

Allocation Debugging - ALLOC_DEBUG

Debugging support: Define this to enable code which helps detect re-use of free()d memory and other such nonsense.

The theory is simple. The FILL_BYTE (0xa5) is written over all malloc'd memory as we receive it, and is written over everything that we free up during a clear_pool. We check that blocks on the free list always have the FILL_BYTE in them, and we check during palloc() that the bytes still have FILL_BYTE in them. If you ever see garbage URLs or whatnot containing lots of 0xa5s then you know something used data that's been freed or uninitialized.

Malloc Support - ALLOC_USE_MALLOC

If defined all allocations will be done with malloc() and free()d appropriately at the end.

This is intended to be used with something like Electric Fence or Purify to help detect memory problems. Note that if you're using efence then you should also add in ALLOC_DEBUG. But don't add in ALLOC_DEBUG if you're using Purify because ALLOC_DEBUG would hide all the uninitialized read errors that Purify can diagnose.

Pool Debugging - POOL_DEBUG

This is intended to detect cases where the wrong pool is used when assigning data to an object in another pool.

In particular, it causes the table_{set,add,merge}n routines to check that their arguments are safe for the apr_table_t they're being placed in. It currently only works with the unix multiprocess model, but could be extended to others.

Table Debugging - MAKE_TABLE_PROFILE

Provide diagnostic information about make_table() calls which are possibly too small.

This requires a recent gcc which supports __builtin_return_address(). The error_log output will be a message such as:

table_push: apr_table_t created by 0x804d874 hit limit of 10

Use l *0x804d874 to find the source that corresponds to. It indicates that a apr_table_t allocated by a call at that address has possibly too small an initial apr_table_t size guess.

Allocation Statistics - ALLOC_STATS

Provide some statistics on the cost of allocations.

This requires a bit of an understanding of how alloc.c works.

top

Allowable Combinations

Not all the options outlined above can be activated at the same time. the following table gives more information.

ALLOC DEBUG ALLOC USE MALLOC POOL DEBUG MAKE TABLE PROFILE ALLOC STATS
ALLOC DEBUG -NoYesYesYes
ALLOC USE MALLOC No-NoNoNo
POOL DEBUG YesNo-YesYes
MAKE TABLE PROFILE YesNoYes-Yes
ALLOC STATS YesNoYesYes-

Additionally the debugging options are not suitable for multi-threaded versions of the server. When trying to debug with these options the server should be started in single process mode.

top

Activating Debugging Options

The various options for debugging memory are now enabled in the apr_general.h header file in APR. The various options are enabled by uncommenting the define for the option you wish to use. The section of the code currently looks like this (contained in srclib/apr/include/apr_pools.h)

/*
#define ALLOC_DEBUG
#define POOL_DEBUG
#define ALLOC_USE_MALLOC
#define MAKE_TABLE_PROFILE
#define ALLOC_STATS
*/

typedef struct ap_pool_t {
union block_hdr *first;
union block_hdr *last;
struct cleanup *cleanups;
struct process_chain *subprocesses;
struct ap_pool_t *sub_pools;
struct ap_pool_t *sub_next;
struct ap_pool_t *sub_prev;
struct ap_pool_t *parent;
char *free_first_avail;
#ifdef ALLOC_USE_MALLOC
void *allocation_list;
#endif
#ifdef POOL_DEBUG
struct ap_pool_t *joined;
#endif
int (*apr_abort)(int retcode);
struct datastruct *prog_data;
} ap_pool_t;

To enable allocation debugging simply move the #define ALLOC_DEBUG above the start of the comments block and rebuild the server.

Note

In order to use the various options the server must be rebuilt after editing the header file.

developer/documenting.html100644 0 0 10201 10422374001 13377 0ustar 0 0 Documenting Apache 2.0 - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > Developer Documentation

Documenting Apache 2.0

Apache 2.0 uses Doxygen to document the APIs and global variables in the the code. This will explain the basics of how to document using Doxygen.

top

Brief Description

To start a documentation block, use /**
To end a documentation block, use */

In the middle of the block, there are multiple tags we can use:

Description of this functions purpose
@param parameter_name description
@return description
@deffunc signature of the function

The deffunc is not always necessary. DoxyGen does not have a full parser in it, so any prototype that use a macro in the return type declaration is too complex for scandoc. Those functions require a deffunc. An example (using &gt; rather than >):

/**
 * return the final element of the pathname
 * @param pathname The path to get the final element of
 * @return the final element of the path
 * @tip Examples:
 * <pre>
 * "/foo/bar/gum" -&gt; "gum"
 * "/foo/bar/gum/" -&gt; ""
 * "gum" -&gt; "gum"
 * "wi\\n32\\stuff" -&gt; "stuff"
 * </pre>
 * @deffunc const char * ap_filename_of_pathname(const char *pathname)
 */

At the top of the header file, always include:

/**
 * @package Name of library header
 */

Doxygen uses a new HTML file for each package. The HTML files are named {Name_of_library_header}.html, so try to be concise with your names.

For a further discussion of the possibilities please refer to the Doxygen site.

developer/filters.html100644 0 0 27701 10422374001 12550 0ustar 0 0 How filters work in Apache 2.0 - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > Developer Documentation

How filters work in Apache 2.0

Warning

This is a cut 'n paste job from an email (<022501c1c529$f63a9550$7f00000a@KOJ>) and only reformatted for better readability. It's not up to date but may be a good start for further research.

top

Filter Types

There are three basic filter types (each of these is actually broken down into two categories, but that comes later).

CONNECTION
Filters of this type are valid for the lifetime of this connection. (AP_FTYPE_CONNECTION, AP_FTYPE_NETWORK)
PROTOCOL
Filters of this type are valid for the lifetime of this request from the point of view of the client, this means that the request is valid from the time that the request is sent until the time that the response is received. (AP_FTYPE_PROTOCOL, AP_FTYPE_TRANSCODE)
RESOURCE
Filters of this type are valid for the time that this content is used to satisfy a request. For simple requests, this is identical to PROTOCOL, but internal redirects and sub-requests can change the content without ending the request. (AP_FTYPE_RESOURCE, AP_FTYPE_CONTENT_SET)

It is important to make the distinction between a protocol and a resource filter. A resource filter is tied to a specific resource, it may also be tied to header information, but the main binding is to a resource. If you are writing a filter and you want to know if it is resource or protocol, the correct question to ask is: "Can this filter be removed if the request is redirected to a different resource?" If the answer is yes, then it is a resource filter. If it is no, then it is most likely a protocol or connection filter. I won't go into connection filters, because they seem to be well understood. With this definition, a few examples might help:

Byterange
We have coded it to be inserted for all requests, and it is removed if not used. Because this filter is active at the beginning of all requests, it can not be removed if it is redirected, so this is a protocol filter.
http_header
This filter actually writes the headers to the network. This is obviously a required filter (except in the asis case which is special and will be dealt with below) and so it is a protocol filter.
Deflate
The administrator configures this filter based on which file has been requested. If we do an internal redirect from an autoindex page to an index.html page, the deflate filter may be added or removed based on config, so this is a resource filter.

The further breakdown of each category into two more filter types is strictly for ordering. We could remove it, and only allow for one filter type, but the order would tend to be wrong, and we would need to hack things to make it work. Currently, the RESOURCE filters only have one filter type, but that should change.

top

How are filters inserted?

This is actually rather simple in theory, but the code is complex. First of all, it is important that everybody realize that there are three filter lists for each request, but they are all concatenated together. So, the first list is r->output_filters, then r->proto_output_filters, and finally r->connection->output_filters. These correspond to the RESOURCE, PROTOCOL, and CONNECTION filters respectively. The problem previously, was that we used a singly linked list to create the filter stack, and we started from the "correct" location. This means that if I had a RESOURCE filter on the stack, and I added a CONNECTION filter, the CONNECTION filter would be ignored. This should make sense, because we would insert the connection filter at the top of the c->output_filters list, but the end of r->output_filters pointed to the filter that used to be at the front of c->output_filters. This is obviously wrong. The new insertion code uses a doubly linked list. This has the advantage that we never lose a filter that has been inserted. Unfortunately, it comes with a separate set of headaches.

The problem is that we have two different cases were we use subrequests. The first is to insert more data into a response. The second is to replace the existing response with an internal redirect. These are two different cases and need to be treated as such.

In the first case, we are creating the subrequest from within a handler or filter. This means that the next filter should be passed to make_sub_request function, and the last resource filter in the sub-request will point to the next filter in the main request. This makes sense, because the sub-request's data needs to flow through the same set of filters as the main request. A graphical representation might help:

Default_handler --> includes_filter --> byterange --> ...

If the includes filter creates a sub request, then we don't want the data from that sub-request to go through the includes filter, because it might not be SSI data. So, the subrequest adds the following:

    
Default_handler --> includes_filter -/-> byterange --> ...
                                    /
Default_handler --> sub_request_core

What happens if the subrequest is SSI data? Well, that's easy, the includes_filter is a resource filter, so it will be added to the sub request in between the Default_handler and the sub_request_core filter.

The second case for sub-requests is when one sub-request is going to become the real request. This happens whenever a sub-request is created outside of a handler or filter, and NULL is passed as the next filter to the make_sub_request function.

In this case, the resource filters no longer make sense for the new request, because the resource has changed. So, instead of starting from scratch, we simply point the front of the resource filters for the sub-request to the front of the protocol filters for the old request. This means that we won't lose any of the protocol filters, neither will we try to send this data through a filter that shouldn't see it.

The problem is that we are using a doubly-linked list for our filter stacks now. But, you should notice that it is possible for two lists to intersect in this model. So, you do you handle the previous pointer? This is a very difficult question to answer, because there is no "right" answer, either method is equally valid. I looked at why we use the previous pointer. The only reason for it is to allow for easier addition of new servers. With that being said, the solution I chose was to make the previous pointer always stay on the original request.

This causes some more complex logic, but it works for all cases. My concern in having it move to the sub-request, is that for the more common case (where a sub-request is used to add data to a response), the main filter chain would be wrong. That didn't seem like a good idea to me.

top

Asis

The final topic. :-) Mod_Asis is a bit of a hack, but the handler needs to remove all filters except for connection filters, and send the data. If you are using mod_asis, all other bets are off.

top

Explanations

The absolutely last point is that the reason this code was so hard to get right, was because we had hacked so much to force it to work. I wrote most of the hacks originally, so I am very much to blame. However, now that the code is right, I have started to remove some hacks. Most people should have seen that the reset_filters and add_required_filters functions are gone. Those inserted protocol level filters for error conditions, in fact, both functions did the same thing, one after the other, it was really strange. Because we don't lose protocol filters for error cases any more, those hacks went away. The HTTP_HEADER, Content-length, and Byterange filters are all added in the insert_filters phase, because if they were added earlier, we had some interesting interactions. Now, those could all be moved to be inserted with the HTTP_IN, CORE, and CORE_IN filters. That would make the code easier to follow.

developer/hooks.html100644 0 0 24650 10422374001 12223 0ustar 0 0 Apache 2.0 Hook Functions - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > Developer Documentation

Apache 2.0 Hook Functions

Warning

This document is still in development and may be partially out of date.

In general, a hook function is one that Apache will call at some point during the processing of a request. Modules can provide functions that are called, and specify when they get called in comparison to other modules.

top

Creating a hook function

In order to create a new hook, four things need to be done:

Declare the hook function

Use the AP_DECLARE_HOOK macro, which needs to be given the return type of the hook function, the name of the hook, and the arguments. For example, if the hook returns an int and takes a request_rec * and an int and is called do_something, then declare it like this:

AP_DECLARE_HOOK(int, do_something, (request_rec *r, int n))

This should go in a header which modules will include if they want to use the hook.

Create the hook structure

Each source file that exports a hook has a private structure which is used to record the module functions that use the hook. This is declared as follows:

APR_HOOK_STRUCT(
APR_HOOK_LINK(do_something)
...
)

Implement the hook caller

The source file that exports the hook has to implement a function that will call the hook. There are currently three possible ways to do this. In all cases, the calling function is called ap_run_hookname().

Void hooks

If the return value of a hook is void, then all the hooks are called, and the caller is implemented like this:

AP_IMPLEMENT_HOOK_VOID(do_something, (request_rec *r, int n), (r, n))

The second and third arguments are the dummy argument declaration and the dummy arguments as they will be used when calling the hook. In other words, this macro expands to something like this:

void ap_run_do_something(request_rec *r, int n)
{
...
do_something(r, n);
}

Hooks that return a value

If the hook returns a value, then it can either be run until the first hook that does something interesting, like so:

AP_IMPLEMENT_HOOK_RUN_FIRST(int, do_something, (request_rec *r, int n), (r, n), DECLINED)

The first hook that does not return DECLINED stops the loop and its return value is returned from the hook caller. Note that DECLINED is the tradition Apache hook return meaning "I didn't do anything", but it can be whatever suits you.

Alternatively, all hooks can be run until an error occurs. This boils down to permitting two return values, one of which means "I did something, and it was OK" and the other meaning "I did nothing". The first function that returns a value other than one of those two stops the loop, and its return is the return value. Declare these like so:

AP_IMPLEMENT_HOOK_RUN_ALL(int, do_something, (request_rec *r, int n), (r, n), OK, DECLINED)

Again, OK and DECLINED are the traditional values. You can use what you want.

Call the hook callers

At appropriate moments in the code, call the hook caller, like so:

int n, ret;
request_rec *r;

ret=ap_run_do_something(r, n);

top

Hooking the hook

A module that wants a hook to be called needs to do two things.

Implement the hook function

Include the appropriate header, and define a static function of the correct type:

static int my_something_doer(request_rec *r, int n)
{
...
return OK;
}

Add a hook registering function

During initialisation, Apache will call each modules hook registering function, which is included in the module structure:

static void my_register_hooks()
{
ap_hook_do_something(my_something_doer, NULL, NULL, APR_HOOK_MIDDLE);
}

mode MODULE_VAR_EXPORT my_module =
{
...
my_register_hooks /* register hooks */
};

Controlling hook calling order

In the example above, we didn't use the three arguments in the hook registration function that control calling order. There are two mechanisms for doing this. The first, rather crude, method, allows us to specify roughly where the hook is run relative to other modules. The final argument control this. There are three possible values: APR_HOOK_FIRST, APR_HOOK_MIDDLE and APR_HOOK_LAST.

All modules using any particular value may be run in any order relative to each other, but, of course, all modules using APR_HOOK_FIRST will be run before APR_HOOK_MIDDLE which are before APR_HOOK_LAST. Modules that don't care when they are run should use APR_HOOK_MIDDLE. (I spaced these out so people could do stuff like APR_HOOK_FIRST-2 to get in slightly earlier, but is this wise? - Ben)

Note that there are two more values, APR_HOOK_REALLY_FIRST and APR_HOOK_REALLY_LAST. These should only be used by the hook exporter.

The other method allows finer control. When a module knows that it must be run before (or after) some other modules, it can specify them by name. The second (third) argument is a NULL-terminated array of strings consisting of the names of modules that must be run before (after) the current module. For example, suppose we want "mod_xyz.c" and "mod_abc.c" to run before we do, then we'd hook as follows:

static void register_hooks()
{
static const char * const aszPre[] = { "mod_xyz.c", "mod_abc.c", NULL };

ap_hook_do_something(my_something_doer, aszPre, NULL, APR_HOOK_MIDDLE);
}

Note that the sort used to achieve this is stable, so ordering set by APR_HOOK_ORDER is preserved, as far as is possible.

Ben Laurie, 15th August 1999

developer/index.html100644 0 0 11361 10422374001 12202 0ustar 0 0 Developer Documentation for Apache 2.0 - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2

Developer Documentation for Apache 2.0

Many of the documents on these Developer pages are lifted from Apache 1.3's documentation. While they are all being updated to Apache 2.0, they are in different stages of progress. Please be patient, and point out any discrepancies or errors on the developer/ pages directly to the dev@httpd.apache.org mailing list.

top

Topics

top

External Resources

developer/modules.html100644 0 0 25570 10422374001 12552 0ustar 0 0 モジュールの Apache 1.3 から Apache 2.0 への移植 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > Developer Documentation

モジュールの Apache 1.3 から Apache 2.0 への移植

この文書は mod_mmap_static モジュールを Apache 2.0 用に移植した時に 学んだ経験をもとに書いた、最初の手引き書です。まだまだ完全じゃないし、 ひょっとすると間違っている部分もあるかもしれませんが、 取っ掛りにはなるでしょう。

top

簡単な変更点

クリーンナップ ルーチン

クリーンナップルーチンは apr_status_t 型である必要があります。 そして、apr_status_t 型の値を返さなくてはなりません。 クリーンナップ中のエラーを通知する必要がなければ、返り値は普通、 ARP_SUCCESS です。たとえエラーを通知したとしても、 すべてのコードがその通知をチェックしたり、 エラーに応じた動作をするわけではないことに気をつけてください。

初期化ルーチン

初期化ルーチンは処理全体から見てしっくりくるような意味を表すように、 名前が変更されました。ですから、mmap_init から mmap_post_config のようにちょっと変更されました。 渡される引数は大幅に変更され、次のようになりました。

データ型

データ型のほとんどは APR に移されました。つまり、 いくつかの名前が前述のように変更されています。 施すべき変更点の簡単な一覧を以下に示します。

top

もっと厄介な変更点…

フックの登録

新しいアーキテクチャでは作成した関数を呼び出すのに 一連のフックを使用します。このフックは、新しい関数 static void register_hooks(void) を使って登録するよう、 モジュールに書き足さなくてはなりません。 この関数は、なにをすべきか一旦理解してしまえば、 十分にわかりやすいものです。 リクエストの処理のあるステージで呼び出さなくてはならない 関数は登録する必要があります。ハンドラは登録する必要はありません。 関数を登録できるフェーズはたくさんあります。 それぞれのフェーズで、関数を呼び出す相対的な順番は、 かなりの程度制御できます。

以下は、mod_mmap_static に追加したコードです:

static void register_hooks(void)
{
    static const char * const aszPre[]={ "http_core.c",NULL };
    ap_hook_post_config(mmap_post_config,NULL,NULL,HOOK_MIDDLE);
    ap_hook_translate_name(mmap_static_xlat,aszPre,NULL,HOOK_LAST);
};

ここでは呼びだすべき二つの関数を登録しています。一つは post_config ステージ用 (ほとんどすべてのモジュール はこれが必要です) で、もう一つは translate_name フェーズ用です。 それぞれの関数は名前は違うけれども形式は同じであることに注意してください。 それでは、形式はどのようになっているでしょうか?

ap_hook_phase_name(function_name, predecessors, successors, position);

三つの位置が定義されています…

位置を定義するには、上記の「位置」を指定し、 修飾子である「先行」と「後行」で手を加えます。 「先行」「後行」は、呼ばれるべき関数のリストです。 「先行」は関数の実行前に呼ばれるもので、 「後行」は実行後に呼ばれるものです。

mod_mmap_static の場合、post_config ステージでは必要ありませんが、 mmap_static_xlat が core モジュールが名前の変換を実行した後に 呼ばれなければなりません。 そこで aszPre を使って HOOK_LAST の修飾子を定義しています。

モジュールの定義

モジュールの定義を作成する際に注意しなければならない ステージの数は激減しています。古い定義は次のようになっていました。

module MODULE_VAR_EXPORT module_name_module =
{
    STANDARD_MODULE_STUFF,
    /* initializer */
    /* dir config creater */
    /* dir merger --- default is to override */
    /* server config */
    /* merge server config */
    /* command handlers */
    /* handlers */
    /* filename translation */
    /* check_user_id */
    /* check auth */
    /* check access */
    /* type_checker */
    /* fixups */
    /* logger */
    /* header parser */
    /* child_init */
    /* child_exit */
    /* post read-request */
};

新しい構造体はとってもシンプルです…

module MODULE_VAR_EXPORT module_name_module =
{
    STANDARD20_MODULE_STUFF,
    /* create per-directory config structures */
    /* merge per-directory config structures  */
    /* create per-server config structures    */
    /* merge per-server config structures     */
    /* command handlers */
    /* handlers */
    /* register hooks */
};

このうちのいくつかは古いものから新しいものに直接読み替えられるもので、 いくつかはそうではありません。どうすればいいのかを要約してみます。

直接読み替えられるステージ:

/* ディレクトリ設定作成関数 */
/* ディレクトリ毎設定構造体作成 */
/* サーバ設定作成関数 */
/* サーバ毎設定構造体作成 */
/* ディレクトリ設定マージ関数 */
/* ディレクトリ毎設定構造体マージ */
/* サーバ設定マージ関数 */
/* サーバ毎設定構造体作成マージ */
/* コマンド・テーブル */
/* コマンド apr_table_t */
/* ハンドラ */
/* ハンドラ */

古い関数の残りのものはフックとして登録されるべきです。 現時点で次のようなフック・ステージが定義されています…

ap_hook_post_config
(以前の _init ルーチンが登録されるべき場所です)
ap_hook_http_method
(リクエストから HTTP メソッドを取得します (互換用))
ap_hook_open_logs
(特定のログのオープン)
ap_hook_auth_checker
(リソースが権限を必要とするかどうかの確認)
ap_hook_access_checker
(モジュール固有の制約の確認)
ap_hook_check_user_id
(ユーザ ID とパスワードの確認)
ap_hook_default_port
(サーバのデフォルト・ポートの取得)
ap_hook_pre_connection
(処理の直前に必要なことを実行。ただし accept 直後に呼ばれる)
ap_hook_process_connection
(プロトコルの処理)
ap_hook_child_init
(子プロセル起動直後)
ap_hook_create_request
(??)
ap_hook_fixups
(応答内容の生成を変更するラスト・チャンス)
ap_hook_handler
(応答内容の生成)
ap_hook_header_parser
(モジュールにヘッダの照会をさせる。ほとんどのモジュールでは使われません。post_read_request を使います)
ap_hook_insert_filter
(フィルタ・チェインにフィルタを挿入)
ap_hook_log_transaction
(リクエストについての情報を記録する)
ap_hook_optional_fn_retrieve
(オプションとして登録された関数の取得)
ap_hook_post_read_request
(リクエストを読みこんだ後、他のフェーズの前に呼ばれる)
ap_hook_quick_handler
リクエストの処理が始まる前に呼ばれる。キャッシュモジュールが 使用している
ap_hook_translate_name
(URI をファイル名に変換する)
ap_hook_type_checker
(文書型の決定と設定。あるいはその片方)
developer/request.html100644 0 0 33224 10422374001 12565 0ustar 0 0 Request Processing in Apache 2.0 - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > Developer Documentation

Request Processing in Apache 2.0

Warning

Warning - this is a first (fast) draft that needs further revision!

Several changes in Apache 2.0 affect the internal request processing mechanics. Module authors need to be aware of these changes so they may take advantage of the optimizations and security enhancements.

The first major change is to the subrequest and redirect mechanisms. There were a number of different code paths in Apache 1.3 to attempt to optimize subrequest or redirect behavior. As patches were introduced to 2.0, these optimizations (and the server behavior) were quickly broken due to this duplication of code. All duplicate code has been folded back into ap_process_request_internal() to prevent the code from falling out of sync again.

This means that much of the existing code was 'unoptimized'. It is the Apache HTTP Project's first goal to create a robust and correct implementation of the HTTP server RFC. Additional goals include security, scalability and optimization. New methods were sought to optimize the server (beyond the performance of Apache 1.3) without introducing fragile or insecure code.

top

The Request Processing Cycle

All requests pass through ap_process_request_internal() in request.c, including subrequests and redirects. If a module doesn't pass generated requests through this code, the author is cautioned that the module may be broken by future changes to request processing.

To streamline requests, the module author can take advantage of the hooks offered to drop out of the request cycle early, or to bypass core Apache hooks which are irrelevant (and costly in terms of CPU.)

top

The Request Parsing Phase

Unescapes the URL

The request's parsed_uri path is unescaped, once and only once, at the beginning of internal request processing.

This step is bypassed if the proxyreq flag is set, or the parsed_uri.path element is unset. The module has no further control of this one-time unescape operation, either failing to unescape or multiply unescaping the URL leads to security reprecussions.

Strips Parent and This Elements from the URI

All /../ and /./ elements are removed by ap_getparents(). This helps to ensure the path is (nearly) absolute before the request processing continues.

This step cannot be bypassed.

Initial URI Location Walk

Every request is subject to an ap_location_walk() call. This ensures that <Location> sections are consistently enforced for all requests. If the request is an internal redirect or a sub-request, it may borrow some or all of the processing from the previous or parent request's ap_location_walk, so this step is generally very efficient after processing the main request.

translate_name

Modules can determine the file name, or alter the given URI in this step. For example, mod_vhost_alias will translate the URI's path into the configured virtual host, mod_alias will translate the path to an alias path, and if the request falls back on the core, the DocumentRoot is prepended to the request resource.

If all modules DECLINE this phase, an error 500 is returned to the browser, and a "couldn't translate name" error is logged automatically.

Hook: map_to_storage

After the file or correct URI was determined, the appropriate per-dir configurations are merged together. For example, mod_proxy compares and merges the appropriate <Proxy> sections. If the URI is nothing more than a local (non-proxy) TRACE request, the core handles the request and returns DONE. If no module answers this hook with OK or DONE, the core will run the request filename against the <Directory> and <Files> sections. If the request 'filename' isn't an absolute, legal filename, a note is set for later termination.

URI Location Walk

Every request is hardened by a second ap_location_walk() call. This reassures that a translated request is still subjected to the configured <Location> sections. The request again borrows some or all of the processing from its previous location_walk above, so this step is almost always very efficient unless the translated URI mapped to a substantially different path or Virtual Host.

Hook: header_parser

The main request then parses the client's headers. This prepares the remaining request processing steps to better serve the client's request.

top

The Security Phase

Needs Documentation. Code is:

switch (ap_satisfies(r)) {
case SATISFY_ALL:
case SATISFY_NOSPEC:
    if ((access_status = ap_run_access_checker(r)) != 0) {
        return decl_die(access_status, "check access", r);
    }

    if (ap_some_auth_required(r)) {
        if (((access_status = ap_run_check_user_id(r)) != 0)
            || !ap_auth_type(r)) {
            return decl_die(access_status, ap_auth_type(r)
                          ? "check user.  No user file?"
                          : "perform authentication. AuthType not set!",
                          r);
        }

        if (((access_status = ap_run_auth_checker(r)) != 0)
            || !ap_auth_type(r)) {
            return decl_die(access_status, ap_auth_type(r)
                          ? "check access.  No groups file?"
                          : "perform authentication. AuthType not set!",
                          r);
        }
    }
    break;

case SATISFY_ANY:
    if (((access_status = ap_run_access_checker(r)) != 0)) {
        if (!ap_some_auth_required(r)) {
            return decl_die(access_status, "check access", r);
        }

        if (((access_status = ap_run_check_user_id(r)) != 0)
            || !ap_auth_type(r)) {
            return decl_die(access_status, ap_auth_type(r)
                          ? "check user.  No user file?"
                          : "perform authentication. AuthType not set!",
                          r);
        }

        if (((access_status = ap_run_auth_checker(r)) != 0)
            || !ap_auth_type(r)) {
            return decl_die(access_status, ap_auth_type(r)
                          ? "check access.  No groups file?"
                          : "perform authentication. AuthType not set!",
                          r);
        }
    }
    break;
}
top

The Preparation Phase

Hook: type_checker

The modules have an opportunity to test the URI or filename against the target resource, and set mime information for the request. Both mod_mime and mod_mime_magic use this phase to compare the file name or contents against the administrator's configuration and set the content type, language, character set and request handler. Some modules may set up their filters or other request handling parameters at this time.

If all modules DECLINE this phase, an error 500 is returned to the browser, and a "couldn't find types" error is logged automatically.

Hook: fixups

Many modules are 'trounced' by some phase above. The fixups phase is used by modules to 'reassert' their ownership or force the request's fields to their appropriate values. It isn't always the cleanest mechanism, but occasionally it's the only option.

top

The Handler Phase

This phase is not part of the processing in ap_process_request_internal(). Many modules prepare one or more subrequests prior to creating any content at all. After the core, or a module calls ap_process_request_internal() it then calls ap_invoke_handler() to generate the request.

Hook: insert_filter

Modules that transform the content in some way can insert their values and override existing filters, such that if the user configured a more advanced filter out-of-order, then the module can move its order as need be. There is no result code, so actions in this hook better be trusted to always succeed.

Hook: handler

The module finally has a chance to serve the request in its handler hook. Note that not every prepared request is sent to the handler hook. Many modules, such as mod_autoindex, will create subrequests for a given URI, and then never serve the subrequest, but simply lists it for the user. Remember not to put required teardown from the hooks above into this module, but register pool cleanups against the request pool to free resources as required.

developer/thread_safety.html100644 0 0 36054 10422374001 13723 0ustar 0 0 Apache 2.0 Thread Safety Issues - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > Developer Documentation

Apache 2.0 Thread Safety Issues

When using any of the threaded mpms in Apache 2.0 it is important that every function called from Apache be thread safe. When linking in 3rd party extensions it can be difficult to determine whether the resulting server will be thread safe. Casual testing generally won't tell you this either as thread safety problems can lead to subtle race conditons that may only show up in certain conditions under heavy load.

top

Global and static variables

When writing your module or when trying to determine if a module or 3rd party library is thread safe there are some common things to keep in mind.

First, you need to recognize that in a threaded model each individual thread has its own program counter, stack and registers. Local variables live on the stack, so those are fine. You need to watch out for any static or global variables. This doesn't mean that you are absolutely not allowed to use static or global variables. There are times when you actually want something to affect all threads, but generally you need to avoid using them if you want your code to be thread safe.

In the case where you have a global variable that needs to be global and accessed by all threads, be very careful when you update it. If, for example, it is an incrementing counter, you need to atomically increment it to avoid race conditions with other threads. You do this using a mutex (mutual exclusion). Lock the mutex, read the current value, increment it and write it back and then unlock the mutex. Any other thread that wants to modify the value has to first check the mutex and block until it is cleared.

If you are using APR, have a look at the apr_atomic_* functions and the apr_thread_mutex_* functions.

top

errno

This is a common global variable that holds the error number of the last error that occurred. If one thread calls a low-level function that sets errno and then another thread checks it, we are bleeding error numbers from one thread into another. To solve this, make sure your module or library defines _REENTRANT or is compiled with -D_REENTRANT. This will make errno a per-thread variable and should hopefully be transparent to the code. It does this by doing something like this:

#define errno (*(__errno_location()))

which means that accessing errno will call __errno_location() which is provided by the libc. Setting _REENTRANT also forces redefinition of some other functions to their *_r equivalents and sometimes changes the common getc/putc macros into safer function calls. Check your libc documentation for specifics. Instead of, or in addition to _REENTRANT the symbols that may affect this are _POSIX_C_SOURCE, _THREAD_SAFE, _SVID_SOURCE, and _BSD_SOURCE.

top

Common standard troublesome functions

Not only do things have to be thread safe, but they also have to be reentrant. strtok() is an obvious one. You call it the first time with your delimiter which it then remembers and on each subsequent call it returns the next token. Obviously if multiple threads are calling it you will have a problem. Most systems have a reentrant version of of the function called strtok_r() where you pass in an extra argument which contains an allocated char * which the function will use instead of its own static storage for maintaining the tokenizing state. If you are using APR you can use apr_strtok().

crypt() is another function that tends to not be reentrant, so if you run across calls to that function in a library, watch out. On some systems it is reentrant though, so it is not always a problem. If your system has crypt_r() chances are you should be using that, or if possible simply avoid the whole mess by using md5 instead.

top

Common 3rd Party Libraries

The following is a list of common libraries that are used by 3rd party Apache modules. You can check to see if your module is using a potentially unsafe library by using tools such as ldd(1) and nm(1). For PHP, for example, try this:

% ldd libphp4.so
libsablot.so.0 => /usr/local/lib/libsablot.so.0 (0x401f6000)
libexpat.so.0 => /usr/lib/libexpat.so.0 (0x402da000)
libsnmp.so.0 => /usr/lib/libsnmp.so.0 (0x402f9000)
libpdf.so.1 => /usr/local/lib/libpdf.so.1 (0x40353000)
libz.so.1 => /usr/lib/libz.so.1 (0x403e2000)
libpng.so.2 => /usr/lib/libpng.so.2 (0x403f0000)
libmysqlclient.so.11 => /usr/lib/libmysqlclient.so.11 (0x40411000)
libming.so => /usr/lib/libming.so (0x40449000)
libm.so.6 => /lib/libm.so.6 (0x40487000)
libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0x404a8000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0x404e7000)
libcrypt.so.1 => /lib/libcrypt.so.1 (0x40505000)
libssl.so.2 => /lib/libssl.so.2 (0x40532000)
libcrypto.so.2 => /lib/libcrypto.so.2 (0x40560000)
libresolv.so.2 => /lib/libresolv.so.2 (0x40624000)
libdl.so.2 => /lib/libdl.so.2 (0x40634000)
libnsl.so.1 => /lib/libnsl.so.1 (0x40637000)
libc.so.6 => /lib/libc.so.6 (0x4064b000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000)

In addition to these libraries you will need to have a look at any libraries linked statically into the module. You can use nm(1) to look for individual symbols in the module.

top

Library List

Please drop a note to dev@httpd.apache.org if you have additions or corrections to this list.

LibraryVersionThread Safe?Notes
ASpell/PSpell ?
Berkeley DB 3.x, 4.x Yes Be careful about sharing a connection across threads.
bzip2 Yes Both low-level and high-level APIs are thread-safe. However, high-level API requires thread-safe access to errno.
cdb ?
C-Client Perhaps c-client uses strtok() and gethostbyname() which are not thread-safe on most C library implementations. c-client's static data is meant to be shared across threads. If strtok() and gethostbyname() are thread-safe on your OS, c-client may be thread-safe.
cpdflib ?
libcrypt ?
Expat Yes Need a separate parser instance per thread
FreeTDS ?
FreeType ?
GD 1.8.x ?
GD 2.0.x ?
gdbm No Errors returned via a static gdbm_error variable
ImageMagick 5.2.2 Yes ImageMagick docs claim it is thread safe since version 5.2.2 (see Change log).
Imlib2 ?
libjpeg v6b ?
libmysqlclient Yes Use mysqlclient_r library variant to ensure thread-safety. For more information, please read http://www.mysql.com/doc/en/Threaded_clients.html.
Ming 0.2a ?
Net-SNMP 5.0.x ?
OpenLDAP 2.1.x Yes Use ldap_r library variant to ensure thread-safety.
OpenSSL 0.9.6g Yes Requires proper usage of CRYPTO_num_locks, CRYPTO_set_locking_callback, CRYPTO_set_id_callback
liboci8 (Oracle 8+) 8.x,9.x ?
pdflib 5.0.x Yes PDFLib docs claim it is thread safe; changes.txt indicates it has been partially thread-safe since V1.91: http://www.pdflib.com/products/pdflib/index.html.
libpng 1.0.x ?
libpng 1.2.x ?
libpq (PostgreSQL) 7.x Yes Don't share connections across threads and watch out for crypt() calls
Sablotron 0.95 ?
zlib 1.1.4 Yes Relies upon thread-safe zalloc and zfree functions Default is to use libc's calloc/free which are thread-safe.
dns-caveats.html100644 0 0 26320 10422374001 11317 0ustar 0 0 DNS と Apache にまつわる注意事項 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

DNS と Apache にまつわる注意事項

本文書の内容は次の一言に尽きます。「Apache が設定ファイルを読み込むときに DNS を使用する必要がないようにして下さい」。Apache が設定ファイルを 読み込むときに DNS を使用する必要がある場合、信頼性の問題 (起動しないかもしれません) やサービス拒否や盗用アタック (他のユーザからヒットを盗むことを含みます) の問題に直面するかもしれません。

top

簡単な例

<VirtualHost www.abc.dom>
ServerAdmin webgirl@abc.dom
DocumentRoot /www/abc
</VirtualHost>

Apache が正常に機能するには、バーチャルホスト毎に必ず二つの 情報が必要になります。それは、 ServerName と、そのサーバが応答するための IP (最低一つ) です。 上記例では IP アドレスを含んでいませんので、Apache は DNS を使用して www.abc.dom を見つけなければなりません。 何らかの理由で設定ファイルを読み込んでいるときに DNS が利用できなかった場合、 バーチャルホストは設定されません。 そして、そのバーチャルホストに対するヒットには応答がなされません (Apache 1.2 以前では起動すらしません)。

www.abc.dom のアドレスが 10.0.0.1 だとします。では、次の設定について考えてみましょう。

<VirtualHost 10.0.0.1>
ServerAdmin webgirl@abc.dom
DocumentRoot /www/abc
</VirtualHost>

現在のリリースでは Apache は DNS 逆引きを使用して このバーチャルホストの ServerName を見つけます。 その逆引きが失敗した場合は部分的にバーチャルホストを無効にします (Apache 1.2 より前では起動すらしません)。 バーチャルホストが名前ベースであれば完全に無効になりますが、 IP ベースであれば概ね動作します。しかしながら、サーバ名を 含む完全な URL を生成しなければならない場合は、正しい URL の生成ができません。

次の例は上記の問題を解決しています。

<VirtualHost 10.0.0.1>
ServerName www.abc.dom
ServerAdmin webgirl@abc.dom
DocumentRoot /www/abc
</VirtualHost>

top

サービス拒否

サービス拒否が起こる場合、(少なくとも) 二つのケースがあります。 Apache 1.2 より前を実行している場合、バーチャルホストのための 上記の二つの DNS 検索のうち一つ失敗すれば起動すらしません。 そしてこの DNS 検索が自分の制御下にすらない場合もありえます。 例えば、abc.dom が顧客のサーバの一つで、 DNS は顧客自身で管理している場合、単に www.abc.dom レコードを削除するだけで、 (1.2 より前の) サーバを起動不能にすることができます。

もう一つのケースは、より気付きにくいものです。 次の設定について考えてみましょう。

<VirtualHost www.abc.dom>
  ServerAdmin webgirl@abc.dom
  DocumentRoot /www/abc
</VirtualHost>

<VirtualHost www.def.dom>
  ServerAdmin webguy@def.dom
  DocumentRoot /www/def
</VirtualHost>

10.0.0.1 を www.abc.dom に、 10.0.0.2 を www.def.dom に割り当てているとします。 また、def.dom は顧客自身の DNS の制御下にあるとします。この設定で、abc.dom に向けられたトラフィック全てを奪うことができる位置に def.dom を設置できています。後は単に www.def.dom が 10.0.0.1 を参照するように 設定するだけです。DNS は顧客側の DNS でコントロールされているので、 www.def.dom レコードが好きな場所を指すように 設定できてしまうのを止めさせることができません。

10.0.0.1 に対するリクエスト (http://www.abc.dom/whatever 形式の URL を入力したユーザからのもの全てを含みます) は、def.dom バーチャルホストで応答されます。 このようなことが何故起こるかもっと良く知るためには、 応答の必要なバーチャルホストへのリクエストに対して、 Apache がどのように整合性を確保するかについて、 深い議論が必要になります。おおざっぱな説明はこちらに記述されています。

top

「主サーバ」アドレス

Apache 1.1 での 名前ベースのバーチャルホストのサポート 追加の際に、 Apache は httpd の実行されているホストの IP アドレスを知る必要が出てきました。このアドレスを得るために、 (もしあれば) グローバルな ServerName を使用するか、 C 言語の関数 gethostname (コマンドプロンプトで hostname とタイプしたときと同じものを返します) を呼び出すかをします。 その後、得られたアドレスで DNS 検索を行ないます。 現在のところ、この DNS 検索を回避する方法はありません。

DNS サーバがダウンして、この検索ができない事態が起こることを 恐れているのであれば、/etc/hosts にホスト名を記述しておくことができます (マシンが正常に起動するように既に設定されているかもしれません)。 その場合、DNS 参照が失敗した場合にマシンが /etc/hosts を使用するように設定していることを確認してください。 その方法は、どの OS を使用しているかに依存しますが、 /etc/resolv.conf/etc/nsswitch.conf を編集することで設定できます。

もし他の理由で DNS を利用する必要がない場合は、 HOSTRESORDER 環境変数を「 local 」に設定することでそのようにできます。以上これらの事柄は、どんな OS 、レゾルバライブラリを使用しているかに依存します。また、 mod_env を使用して環境変数を制御しない限り、 CGI にも影響を与えます。man ページや使用している OS の FAQ で調べると良いでしょう。

top

以上の問題を解決する方法

top

付録: 将来的な方向性

DNS に関して、現状は全く宜しくありません。Apache 1.2 で、 DNS のイベントが失敗しても少なくとも起動プロセスが続くようにしましたが、 これが最高の解決方法ではないでしょう。アドレスの再割り当てが必要不可避 となっている今日のインターネットにおいては、 設定ファイルの中で明示的な IP アドレスを要求する仕様は、 全く宜しくありません。

盗用のサービスアタックに関して行なうべき事は、 DNS 順引きを行なって得られたアドレスに対する DNS 逆引きを行なって、二つの名前を比較することです。 この二つが一致しなければバーチャルホストは無効になるようにします。 こうするためには逆引き DNS が適切に設定されている必要があります (FTP サーバや TCP ラッパーのおかげで「二重逆引き」DNS は一般的に なっていますので、管理者にはお馴染みものでしょう)。

IP アドレスが使用されていなくて DNS が失敗した場合は、 どうしてもバーチャルホストウェブサーバを信頼性を確保して 起動させることは不可能のようです。 設定の一部を無効にするというような部分的な解決では、 サーバが何をするようにするかにもよりますが、 そのサーバが起動しないより確実に悪い状況になるでしょう。

HTTP/1.1 が開発され、ブラウザやプロキシが Host ヘッダを発行するようになったので、IP ベースのバーチャルホストを 全く使用しなくても済むようになるかもしれません。 この場合、ウェブサーバは設定中に DNS 参照をしなくても済みます。 しかし 1997 年 3 月時点の状況では、 商用レベルのウェブサーバで使用できるほどには、 これらの機能は広く開発が進んでいません。

dso.html100644 0 0 37234 10422374001 7702 0ustar 0 0 動的共有オブジェクト (DSO) サポート - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

動的共有オブジェクト (DSO) サポート

Apache HTTP サーバはモジュール化されたプログラムで、 管理者がモジュールを選択することでサーバに組み込む機能を選ぶことができます。 モジュールはサーバがビルドされるときに httpd バイナリに 静的に組み込むことができます。もしくは、httpd バイナリとは 別に存在する動的共有オブジェクト (訳注: Dynamic Shared Object) (DSO) としてコンパイルすることも できます。DSO モジュールはサーバがビルドされるときにコンパイルしたり、 Apache 拡張ツール (apxs) を 使って後でコンパイルして追加したりできます。

この文書は DSO モジュールの使い方と、仕組みについて 説明します。

top

実装

個々の Apache モジュールをロードするための DSO サポートは mod_so.c というモジュールの機能に基づいています。 このモジュール は Apache のコアに静的に組み込まれている必要があります。 それは core.c 以外では DSO にできない唯一の モジュールです。事実上、他のすべての Apache のモジュールは、 インストールの文書で説明されているように、 configure--enable-module=shared オプションでそれぞれを DSO ビルドにすることにより、DSO モジュールにすることができます。 mod_foo.so のような DSO にモジュールがコンパイルされれば、 httpd.conf ファイル中で mod_soLoadModule ディレクティブを使うことでサーバの起動や再起動時にこのモジュールを ロードするようにできます。

Apache モジュール用の (特にサードパーティモジュールの) DSO ファイルの 作成を簡単にするために、apxs (APache eXtenSion) という新しいサポートプログラムがあります。 Apache のソースツリーの外で DSO モジュールをビルドするために 使うことができます。発想は単純です: Apache のインストール時の configuremake install のときに Apache の C ヘッダをインストールし、DSO ビルド用のプラットフォーム依存の コンパイラとリンカのフラグを apxs プログラムに追加します。 これにより、ユーザが Apache の配布ソースツリーなしで、さらに DSO サポートのためのプラットフォーム依存のコンパイラやリンカの フラグをいじることなく Apache のモジュールのソースをコンパイル できるようになります。

top

使用法の概要

Apache 2.0 の DSO 機能の概略を知ることができるための、 短く簡潔な概要です:

  1. 配布されている Apache モジュール、仮に mod_foo.c として、それを DSO mod_foo.so にビルド、インストール:

    $ ./configure --prefix=/path/to/install --enable-foo=shared
    $ make install

  2. サードパーティ Apache モジュール、仮に mod_foo.c として、それを DSO mod_foo.so にビルド、インストール:

    $ ./configure --add-module=module_type:/path/to/3rdparty/mod_foo.c \
    --enable-foo=shared
    $ make install

  3. 共有モジュールの 後々のインストール のために Apache を設定:

    $ ./configure --enable-so
    $ make install

  4. サードパーティ Apache モジュール、仮に mod_foo.c として、それを apxs を使って Apache ソースツリーの外で DSO にビルド、インストール:

    $ cd /path/to/3rdparty
    $ apxs -c mod_foo.c
    $ apxs -i -a -n foo mod_foo.la

どの場合においても、共有モジュールをコンパイルした後で、 httpd.confLoadModule ディレクティブを使って Apache がモジュールを使用するように しなければなりません。

top

背景

最近の Unix 系の OS には 動的共有オブジェクト (DSO) の動的リンク/ロードという気のきいた機構が 存在します。これは、実行時にプログラムのアドレス空間に ロードできるような特別な形式でプログラムをビルドすることを 可能にします。

このロードは二つの方法で行なうことができます: 実行プログラムが 起動されたときに ld.so というシステムプログラム により自動的に行なわれる方法と、実行プログラム中から、システムコール dlopen()/dlsym() による Unix ローダへの プログラムシステムのインタフェースを使って手動で行なう方法とが あります。

最初の方法では DSO は普通は共有ライブラリDSO ライブラリ と呼ばれていて、DSO の名前は libfoo.solibfoo.so.1.2 のようになっています。 これらはシステムディレクトリ (通常 /usr/lib) に存在し、 実行プログラムへのリンクはビルド時に -lfoo をリンカに 指定することで確立されます。これによりライブラリへの参照が実行プログラムの ファイルに書き込まれて、起動時に Unix のローダが /usr/lib や、 リンカの -R のようなオプションによりハードコードされたパス、 環境変数 LD_LIBRARY_PATH により設定されたパス、の中から libfoo.so の場所を見つけることができます。それから、 実行プログラム中の (まだ未解決の) シンボルを DSO にあるシンボルで 解決します。

普通は実行プログラム中のシンボルは DSO からは参照されません (DSO は一般的なコードによる再利用可能なライブラリですので)。 ですから、さらなるシンボルの解決は必要ありません。 シンボルは Unix ローダにより完全な解決が行なわれますので、実行ファイル自身は 何もする必要がありません。(実際のところ、静的でない方法でリンクされている すべての実行プログラムに組み込まれている開始用のコードの一部に ld.so を起動するコードが含まれています)。よく使われる ライブラリの動的ロードの利点は明らかです。ライブラリのコードは システムライブラリに libc.so のようにして一度保存するだけでよく、 プログラムのために必要なディスクの領域を節約することができます。

二つめの方法では DSO は普通は共有オブジェクトDSO ファイルと呼ばれていて、任意の拡張子を付けることができます (ただし、標準的な名前は foo.so です)。 これらのファイルは通常はプログラム専用のディレクトリに置かれ、 これらを使う実行プログラムへのリンクは自動的にはされません。 ですので、実行プログラムは dlopen() を使って 実行時に手動で DSO をプログラムのアドレス空間にロードする必要があります。 この時点では実行プログラムに対して DSO のシンボルの解決は行なわれません。 しかし、その代わりに Unix のローダが DSO の (まだ未解決の) シンボルを 実行プログラムによりエクスポートされたシンボルと既にロードされた DSO ライブラリによりエクスポートされたシンボル (特に、どこにでもある libc.so のすべてのシンボル) で自動的に解決します。 こうすることで、DSO は最初から静的にリンクされていたかのように、 実行プログラムのシンボルを知ることができます。

最後に、DSO の API を利点を生かすために、プログラムは 後でディスパッチテーブルなどでシンボルを使うことができるように、 dlsym() を使っていくつかのシンボルを解決します。 すなわち: 実行プログラムは必要なすべてのシンボルを手動で解決しなければ なりません。この機構の利点はプログラムのオプショナルな部分は 必要になるまでロードする必要がない (だからメモリも消費しない) ことです。必要ならば、基本プログラムの機能を拡張するために これらの部分を動的にロードすることができます。

この DSO 機構は簡単なように見えますが、少なくとも一つ難しい点が あります: プログラムを拡張するために DSO を使っているときに、 DSO が実行プログラムからシンボルを解決する点です (二番目の方法)。 これはなぜでしょうか。それは、DSO のシンボルを実行プログラムの シンボルから「逆解決」するというのはライブラリの設計 (ライブラリはそれを使用するプログラムのことは何も 知らない) に反していて、この機能はすべてのプラットフォームに あるわけではなく、標準化もされていないからです。 実際には実行プログラムのグローバルなシンボルは再エクスポートされることは あまりなく、DSO から使うことができません。リンカにグローバルシンボルすべてを エクスポートするようにさせる方法を見つけることが、実行時にプログラムを 拡張するために DSO を使うときの一番の問題です。

共有ライブラリのアプローチが普通の方法です。DSO 機構はそのために 設計されたものですから。したがって、その方法はオペレーティングシステムが 提供するほとんどすべての種類のライブラリで使われています。 一方、プログラムの拡張のために共有オブジェクトを使用する、という方は あまり使われていません。

1998 年の時点で、実行時に実際に機能拡張のために DSO 機構を使っている ソフトウェアパッケージは少しだけでした: Perl 5 (XS 機構と DnaLoader モジュール によるもの)、Netscape サーバなどです。Apache はすでに モジュールの概念を使って機能拡張をしていて、内部的にディスパッチリストに 基づいた外部モジュールの Apache コア機能へのリンクを行なっていましたので、 バージョン 1.3 から、Apache も DSO 機構を使う仲間になりました。 Apache は実行時に DSO を使ってモジュールをロードするようにすでに 運命付けられていたのです。

top

利点と欠点

上記の DSO に基づいた機能は以下の利点があります:

DSO には以下の欠点があります:

env.html100644 0 0 53010 10422374001 7673 0ustar 0 0 Apache の環境変数 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

Apache の環境変数

Apache HTTP サーバは環境変数と呼ばれる、名前のついた 変数に情報を記憶する仕組みを提供しています。この情報はログ収集や アクセス制御などのいろいろな操作を制御するために使うことができます。 これらの変数は CGI スクリプトなどの外部プログラムと通信するためにも 使われます。この文書はそれらの変数の操作方法と使用方法をいくつか 紹介します。

これらの変数は環境変数と呼ばれていますが、オペレーティング システムによって制御されている環境変数と同じではありません。 実際は、これらの変数は Apache の内部構造の中に記憶され、操作されています。 それらは、CGI や SSI スクリプトに渡されたときだけ、実際の オペレーティングシステムの環境変数になります。サーバ自身が 実行されているオペレーティングシステムの環境を操作したい場合は、 オペレーティングシステムのシェルが提供している標準の環境変数の 操作方法を使わなければなりません。

top

環境変数の設定

基本的な環境の操作

Apache において環境変数を設定する一番基本的な方法は、 無条件に環境変数を設定する SetEnv ディレクティブを使用することです。 PassEnv ディレクティブにより、Apache が起動されたシェルの 環境変数を渡すこともできます。

リクエスト毎に条件に基づいて設定する

より柔軟性を高めるために、mod_setenvif で提供されているディレクティブを使用することで、リクエストの 特性に基づいて環境変数を設定することができます。例えば、特定のブラウザ (User-Agent) のリクエストや特定の Referer [意図的な綴りです] (訳注: 正しい綴りは referrer ですが、HTTP の仕様では Referer となっています) ヘッダが見つかったときのみ変数を設定することができます。 mod_rewrite の RewriteRule ディレクティブにおいて環境変数を設定する [E=...] オプションを使用することで、 より柔軟な設定を行なうことができます。

一意な識別子

mod_unique_id は、非常に限られた条件の下で 「すべて」のリクエストについて、一意であることが保証されている値を環境変数 UNIQUE_ID に設定します。

標準 CGI 変数

Apache の設定ファイルで設定された環境変数とシェルから渡される 環境変数に加えて、CGI スクリプトと SSI ページには CGI の仕様で要求されている、 リクエストのメタ情報を持った環境変数の組が提供されます。

いくつかの注意

top

環境変数の使用

CGI スクリプト

環境変数の主な利用法の一つは、CGI スクリプトに情報を伝えることです。 上で説明されているように、CGI スクリプトに渡される環境変数は Apache の設定により設定される変数に加えて、リクエストの標準のメタ情報を含んでいます。 詳細は CGI チュートリアル を参照してください。

SSI ページ

mod_include の INCLUDES フィルタで処理される server-parsed (SSI) ドキュメントでは、echo 要素を使用すると環境変数が出力されます。 また、ページのある部分がリクエストの性質に応じて変更されるように、 環境変数をフロー制御要素で使うことができます。詳細は SSI チュートリアル を参照してください。

アクセス制御

allow from env= ディレクティブと deny from env= ディレクティブを使用して、サーバへのアクセスを環境変数の値で制御することができます。 SetEnvIf ディレクティブと組み合わせることで、クライアントの特性に基づいて サーバへのアクセス制御を柔軟に行なうことができるようになります。 たとえば、これらのディレクティブを使用して、特定のブラウザ (User-Agent) からのアクセスを拒否することができます。

条件付きログ記録

LogFormat ディレクティブのオプション %e を使用することで、環境変数をアクセスログに記録することができます。さらに、 CustomLog ディレクティブの条件分岐式を使用することで、 環境変数の値によってリクエストをログに記録するかどうかを決めることができます。 SetEnvIf ディレクティブと組み合わせることで、 どのリクエストをログに記録するかを柔軟に制御することが可能になります。たとえば、 gif で終わるファイル名へのリクエストはログに記録しない、 違うサブネットのクライアントからのリクエストだけをログに記録する、 という選択が可能です。

条件付き応答ヘッダ

Header ディレクティブは環境変数の存在や不在によってクライアントへの応答に特定の HTTP ヘッダを付けるかどうかを決めることができます。 これにより、たとえば、クライアントからのリクエスト にあるヘッダがある場合にのみ特定の応答ヘッダを送る、というようなことが できます。

外部フィルタの適用

ExtFilterDefine ディレクティブを使用して mod_ext_filter で設定される外部フィルタは、 disableenv=enableenv= オプションを使って、環境変数による条件付き適用ができます。

URL の書き換え

RewriteCond ディレクティブで評価文字列として %{ENV:...} 式を指定することで、mod_rewrite の書き換えエンジンが環境変数に基いて条件分岐を行なうことができます。 mod_rewrite が使用可能な変数で ENV: が前についていない変数は、 実際は環境変数ではないということに注意してください。 それらは他のモジュールからは使用できない mod_rewrite 用の特別な変数です。

top

特別な目的の環境変数

互換性の問題を解決するために、特定のクライアントと通信しているときは Apache の動作を変更できる機構が導入されました。できるだけ柔軟にするために、 これらの機構は環境変数を定義することで呼び出されます。普通は、 BrowserMatch ディレクティブを使いますが、たとえば SetEnv ディレクティブや PassEnv ディレクティブも使用することができます。

downgrade-1.0

これを指定することで、リクエストが HTTP/1.0 より新しいプロトコルの場合でも、HTTP/1.0 として扱われます。

force-gzip

DEFLATE フィルタが使用するように設定されているときに、 この環境変数はブラウザの accept-encoding の設定を無視して常に 圧縮された出力を送るようにします。

force-no-vary

応答ヘッダがクライアントに送られる前に Vary フィールドを取り除きます。 クライアントの中にはこのフィールドを正しく解釈しないものがあります。 この変数を設定することでその問題を回避することができます。 この変数を設定すると、force-response-1.0 が設定されたことになります。

force-response-1.0

これが設定されていると、HTTP/1.0 リクエストを発行するクライアントに対しては 常に HTTP/1.0 で応答するようになります。この機能は、 元々は AOL のプロキシの問題のために実装されました。HTTP/1.0 クライアントの中には、 HTTP/1.1 の応答を返されると正しく動作しないものがあるかもしれません。 この機能を使用することで、そのようなクライアントとの間の互換性問題を解決できます。

gzip-only-text/html

これが 1 に設定されると、この変数は text/html 以外のコンテントタイプに対する、mod_deflate 提供の DEFLATE 出力フィルタを無効にします。 また、静的に、既に圧縮されたファイルを使用したい場合、 (gzip だけでなく、"identity" と異なる全てのエンコードに対して) mod_negotiation も変数を評価します。

no-gzip

セットされると、mod_deflateDEFLATE フィルタがオフになります。 そして mod_negotiation はエンコードされたリソースを送らないようにします。

nokeepalive

これが設定されている場合は、KeepAlive を使用しないようにします。

prefer-language

mod_negotiation の挙動に影響を与えます。 (en, ja, x-klingonといった) 言語タグが格納されていれば、その言語の variant を送信しようとします。 そのような variant がない場合は、 通常のネゴシエーション処理が 適用されます。

redirect-carefully

これはクライアントへのリダイレクトの送信をサーバがより注意深く 行なうようにします。 これは通常、リダイレクトに際してクライアントに 問題があることが分かっている場合に使われます。この機能は元々は マイクロソフトのウェブフォルダのソフトが DAV メソッドによるディレクトリのリソースへのリダイレクトの扱いに 問題がり、それを回避するために実装されました。

suppress-error-charset

Apache 2.2 以降で利用可能

クライアントのリクエストに対する応答としてリダイレクトを送信する際、 レスポンスにはリダイレクトが自動的に行なえない (行なわれない) 場合に表示するテキストが含まれます。 通常、このテキストに合致したキャラクタセット、ISO-8859-1 でラベル付けをします。

しかし、リダイレクト先が別の文字セットを使っている場合、 ある問題のあるブラウザのバージョンでは、 リダイレクト先の実際の文字セットの代わりに、 リダイレクト元の文字セットを使ってしまうことがあります。 その結果、例えば変な描画が行なわれたりして、読めなくなったりします。

この環境変数を設定することで、リダイレクションテキストに対する キャラクタセットの指定を除去しますので、それら問題のあるブラウザでも リダイレクト先の文字セットを正しく使うようにできます。

force-proxy-request-1.0, proxy-nokeepalive, proxy-sendchunked, proxy-sendcl

これらの指示子は mod_proxy の挙動を変更します。 詳細は mod_proxy のドキュメントをご参照ください。

top

おかしな挙動をするクライアントに対してプロトコルの動作を変更する

クライアントに関する既知の問題に対処するために、以下の行を httpd.conf に入れることを推奨しています。

古いバージョンの Apache では、クライアントの問題に対応するために httpd.conf に次の行を加えるよう推奨されていましたが、 今となっては、問題としていたクライアントは実際には見かけることは なくなってきたので、この設定はもはや必要ないかもしれません。

#
# The following directives modify normal HTTP response behavior.
# The first directive disables keepalive for Netscape 2.x and browsers that
# spoof it. There are known problems with these browser implementations.
# The second directive is for Microsoft Internet Explorer 4.0b2
# which has a broken HTTP/1.1 implementation and does not properly
# support keepalive when it is used on 301 or 302 (redirect) responses.
#
BrowserMatch "Mozilla/2" nokeepalive
BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0

#
# The following directive disables HTTP/1.1 responses to browsers which
# are in violation of the HTTP/1.0 spec by not being able to grok a
# basic 1.1 response.
#
BrowserMatch "RealPlayer 4\.0" force-response-1.0
BrowserMatch "Java/1\.0" force-response-1.0
BrowserMatch "JDK/1\.0" force-response-1.0

画像へのリクエストをアクセスログに記録しない

この例では、画像へのリクエストがアクセスログに現れないようにします。 これを変更することで、特定のディレクトリのログ収集をやめたり、 特定のホストからのリクエストのログ収集をやめたりすることが簡単にできます。

SetEnvIf Request_URI \.gif image-request
SetEnvIf Request_URI \.jpg image-request
SetEnvIf Request_URI \.png image-request
CustomLog logs/access_log common env=!image-request

「画像の盗用」を防ぐ

この例は、別のサーバにいる人が、あなたのサーバにある画像を inline 画像として使用することを防ぎます。 これは推奨されている設定ではありませんが、ある限定された状況では有効です。 ここでは、すべての画像は /web/images というディレクトリにあると仮定します。

SetEnvIf Referer "^http://www.example.com/" local_referal
# Allow browsers that do not send Referer info
SetEnvIf Referer "^$" local_referal
<Directory /web/images>
   Order Deny,Allow
   Deny from all
   Allow from env=local_referal
</Directory>

この手法に関する詳しい情報は ApacheToday のチュートリアル「Keeping Your Images from Adorning Other Sites 」を参照してください。

faq/all_in_one.html100644 0 0 24223 10422374001 11755 0ustar 0 0 よくある質問 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > FAQ

よくある質問

This translation may be out of date. Check the English version for recent changes.

Apache の主サイト、<http://httpd.apache.org/docs/2.2/faq/> から最新版の FAQ を常に手に入れることができます。

Apache 2.0 はまだ新しいので、何がよくある質問なのか まだよくわかっていません。このセクションが埋まっていくまで、 既に質問が答えられているかどうか Apache 1.3 の FAQ も見るようにしてください。

top

トピック

サポート
何か問題が起こったときにどうする?
エラーメッセージ
このエラーメッセージの意味は?
top

サポート

「なんで…? どうして動作しない…?」問題が 起きたときにどうするか

Apache のサーバソフトウェアに何か問題が起こったときは、以下の 手順に従ってください:

エラーログを調べる!
問題が発生したときは Apache はなるべく手助けをしようとします。 多くの場合、Apache はサーバのエラーログにメッセージを書くことで、詳細な 情報を提供します。場合によっては、これだけで問題を自分自身で分析し、 修正するために十分な情報を得ることができます (ファイルのパーミッションの 問題など)。エラーログのデフォルトの場所は /usr/local/apache2/logs/error_log ですが、あなたのサーバ での場所を知るためには設定ファイル中の ErrorLog を見てください。
FAQ を調べる!
Apache のよくある質問の最新版は常に Apache の主ウェブサイトに あります。
Apache バグデータベースを調べる
Apache グループに報告されるほとんどの問題はバグデータベースに 記録されます。Open closed 含めて、 既存のレポートにあるかどうかを調べてください。 既に問題が報告されているとき、「私も」という報告は追加しないで ください。元の報告が close されていないときは、定期的に バグデータベースを調べることをお薦めします。また、元の提出者に 連絡を取ることも考慮に入れておくとよいでしょう。データベースに 記録されていない電子メールの交換が行なわれているかもしれません。
ユーザサポートフォーラムで質問する

Apache にはよろこんで知識を共有させてくれる活発な ユーザのコミュニティがあります。このコミュニティに参加することが、 普通は質問や問題に対する回答を得る最善で最速の手段です。

ユーザ メーリングリスト

USENET ニュースグループ:

もし、全部失敗した場合は、問題をバグデータベースに報告してください

上記の手段の中で該当するものををすべて取って、 それでも問題の解決策を得られなかった場合は、バグの報告を することにより、問題をぜひ httpd 開発者に知らせてください。

サーバのクラッシュやコアダンプの発生する問題であれば、(可能であれば) バックトレースを報告に含めてください。例えば、

# cd ServerRoot
# dbx httpd core
(dbx) where

(ServerRoothttpdcore ファイル の位置を適切なものに置き換えてください。dbx の代わりに gdb を使う必要があるかもしれません。)

誰にサポートを頼めばよい?

数百万のユーザに対して、40未満のボランティア開発者しかいないため、 Apache の個人的なサポートを提供することはできません。無料の サポートには、ユーザのフォーラムに参加するのが良いでしょう。

Apache のプロの、商用サポートも 多くの会社 から提供されています。

top

エラーメッセージ

Invalid argument: core_output_filter: writing data to the network

(訳注: 無効な引数: core_output_filter: ネットワークへのデータの 書き込み)

Apache は応答の返送を速くするために、sendfile システム コールが使用可能なプラットフォームではそのシステムコールを使用します。 ところが、都合の悪いことに、sendfile が正しく動作しないにも 関わらず、Apache がコンパイル時に存在を検知してしまうシステムがあります。 これは、ネットワークファイルシステムや他の非標準のファイルシステムを 使用しているときに一番よく発生します。

この問題の症状は、上記のメッセージがエラーログに書かれることと、 サイズがゼロでないファイルの応答がゼロになることです。 動的なコンテンツは sendfile を利用しないため、 この問題は通常は静的なファイルでのみ発生します。

この問題は、EnableSendfile ディレクティブを使用して、 サーバのすべて、もしくは一部分に対して sendfile を 無効にするだけで修正できます。同様の問題を解決するための EnableMMAP ディレクティブも 参照してください。

AcceptEx Failed

(訳注: AcceptEx 失敗)

Win32 での AcceptEx システムコールに関係するエラー メッセージを受け取ったときは、Win32DisableAcceptEx を参照してください。

Premature end of script headers

(訳注: スクリプトヘッダの中途終了)

CGI スクリプトのほとんどの問題はエラーログにこのメッセージが書かれ、 ブラウザには Internal Server Error が送られることになります。 この種の問題のデバッグ方法は CGI チュートリアル で説明されています。

faq/background.html100644 0 0 13376 10422374001 12004 0ustar 0 0 Background - Frequently Asked Questions - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > FAQ

Background - Frequently Asked Questions

top

Background

What is Apache?

The Apache Software Foundation (ASF) is a 501(c)3 non-profit organization providing support for the Apache community of open-sourced software projects. For more details, please see the Apache Software Foundation FAQ

The Apache HTTP Server -- sometimes called Apache httpd -- is a project of the Apache Software foundation aimed at creating a robust, commercial-grade, featureful, and freely-available source code implementation of an HTTP (Web) server. For more information, please see the About Apache page.

What is the Apache HTTP Server?

How thoroughly tested is Apache?

Apache is run on millions of Internet servers. It has been tested thoroughly by both developers and users. The Apache HTTP Server Project maintains rigorous standards before releasing new versions of our server, and our server runs without a hitch on over 70% of all WWW servers available on the Internet. When bugs do show up, we release patches and new versions as soon as they are available.

You may NOT use any original artwork from the Apache Software Foundation, nor make or use modified versions of such artwork, except under the following conditions:

faq/error.html100644 0 0 11045 10422374001 11005 0ustar 0 0 エラーメッセージ ― よくある質問 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > FAQ

エラーメッセージ ― よくある質問

This translation may be out of date. Check the English version for recent changes.
top

エラーメッセージ

Invalid argument: core_output_filter: writing data to the network

(訳注: 無効な引数: core_output_filter: ネットワークへのデータの 書き込み)

Apache は応答の返送を速くするために、sendfile システム コールが使用可能なプラットフォームではそのシステムコールを使用します。 ところが、都合の悪いことに、sendfile が正しく動作しないにも 関わらず、Apache がコンパイル時に存在を検知してしまうシステムがあります。 これは、ネットワークファイルシステムや他の非標準のファイルシステムを 使用しているときに一番よく発生します。

この問題の症状は、上記のメッセージがエラーログに書かれることと、 サイズがゼロでないファイルの応答がゼロになることです。 動的なコンテンツは sendfile を利用しないため、 この問題は通常は静的なファイルでのみ発生します。

この問題は、EnableSendfile ディレクティブを使用して、 サーバのすべて、もしくは一部分に対して sendfile を 無効にするだけで修正できます。同様の問題を解決するための EnableMMAP ディレクティブも 参照してください。

AcceptEx Failed

(訳注: AcceptEx 失敗)

Win32 での AcceptEx システムコールに関係するエラー メッセージを受け取ったときは、Win32DisableAcceptEx を参照してください。

Premature end of script headers

(訳注: スクリプトヘッダの中途終了)

CGI スクリプトのほとんどの問題はエラーログにこのメッセージが書かれ、 ブラウザには Internal Server Error が送られることになります。 この種の問題のデバッグ方法は CGI チュートリアル で説明されています。

faq/index.html100644 0 0 5570 10422374001 10751 0ustar 0 0 よくある質問 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

よくある質問

This translation may be out of date. Check the English version for recent changes.

Apache の主サイト、<http://httpd.apache.org/docs/2.2/faq/> から最新版の FAQ を常に手に入れることができます。 また、簡単な検索や印刷のためにこの FAQ の 一ページ版もあります。

Apache 2.0 はまだ新しいので、何がよくある質問なのか まだよくわかっていません。このセクションが埋まっていくまで、 既に質問が答えられているかどうか Apache 1.3 の FAQ も見るようにしてください。

top

トピック

サポート
何か問題が起こったときにどうする?
エラーメッセージ
このエラーメッセージの意味は?
faq/support.html100644 0 0 15136 10422374001 11375 0ustar 0 0 サポート ― よくある質問 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > FAQ

サポート ― よくある質問

This translation may be out of date. Check the English version for recent changes.
top

サポート

「なんで…? どうして動作しない…?」問題が 起きたときにどうするか

Apache のサーバソフトウェアに何か問題が起こったときは、以下の 手順に従ってください:

エラーログを調べる!
問題が発生したときは Apache はなるべく手助けをしようとします。 多くの場合、Apache はサーバのエラーログにメッセージを書くことで、詳細な 情報を提供します。場合によっては、これだけで問題を自分自身で分析し、 修正するために十分な情報を得ることができます (ファイルのパーミッションの 問題など)。エラーログのデフォルトの場所は /usr/local/apache2/logs/error_log ですが、あなたのサーバ での場所を知るためには設定ファイル中の ErrorLog を見てください。
FAQ を調べる!
Apache のよくある質問の最新版は常に Apache の主ウェブサイトに あります。
Apache バグデータベースを調べる
Apache グループに報告されるほとんどの問題はバグデータベースに 記録されます。Open closed 含めて、 既存のレポートにあるかどうかを調べてください。 既に問題が報告されているとき、「私も」という報告は追加しないで ください。元の報告が close されていないときは、定期的に バグデータベースを調べることをお薦めします。また、元の提出者に 連絡を取ることも考慮に入れておくとよいでしょう。データベースに 記録されていない電子メールの交換が行なわれているかもしれません。
ユーザサポートフォーラムで質問する

Apache にはよろこんで知識を共有させてくれる活発な ユーザのコミュニティがあります。このコミュニティに参加することが、 普通は質問や問題に対する回答を得る最善で最速の手段です。

ユーザ メーリングリスト

USENET ニュースグループ:

もし、全部失敗した場合は、問題をバグデータベースに報告してください

上記の手段の中で該当するものををすべて取って、 それでも問題の解決策を得られなかった場合は、バグの報告を することにより、問題をぜひ httpd 開発者に知らせてください。

サーバのクラッシュやコアダンプの発生する問題であれば、(可能であれば) バックトレースを報告に含めてください。例えば、

# cd ServerRoot
# dbx httpd core
(dbx) where

(ServerRoothttpdcore ファイル の位置を適切なものに置き換えてください。dbx の代わりに gdb を使う必要があるかもしれません。)

誰にサポートを頼めばよい?

数百万のユーザに対して、40未満のボランティア開発者しかいないため、 Apache の個人的なサポートを提供することはできません。無料の サポートには、ユーザのフォーラムに参加するのが良いでしょう。

Apache のプロの、商用サポートも 多くの会社 から提供されています。

filter.html100644 0 0 12437 10422374001 10400 0ustar 0 0 フィルタ - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

フィルタ

This translation may be out of date. Check the English version for recent changes.

Apache でのフィルタの使い方について記述しています。

top

フィルタ

フィルタ とは、サーバが送受信したデータに 適用される処理プロセスのことをいいます。クライアントからサーバに 送られたデータは 入力フィルタ によって、サーバから クライアントに送られるデータは出力フィルタによって 処理されます。複数のフィルタを適用することができ、 その順番を厳密に指定することもできます。

Apache 内部では、チャンク (データのぶつ切り) を行ったり、 バイト範囲の指定されたリクエストを扱ったりといった機能を 行う際に、フィルタが使われています。それに加えて、 実行時の設定ディレクティブで選択が可能なフィルタを モジュールが提供できます。 データに適応されるフィルタのセットは、 SetInputFilter, SetOutputFilter, AddInputFilter, AddOutputFilter, RemoveInputFilter, RemoveOutputFilter ディレクティブで制御できます。

現行の Apache HTTP サーバの配布では、 次のユーザ選択可能なフィルタが提供されています。

INCLUDES
mod_include で Server-Side Include をします。
DEFLATE
mod_deflate を使って、クライアントに送信する前に出力を圧縮します。

また、mod_ext_filter モジュールで 外部プログラムをフィルタとして指定することができます。

glossary.html100644 0 0 61631 10422374001 10756 0ustar 0 0 Glossary - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2

Glossary

This glossary defines some of the common terminology related to Apache in particular, and web serving in general. More information on each concept is provided in the links.

top

Definitions

Access Control
The restriction of access to network realms. In an Apache context usually the restriction of access to certain URLs.
See: Authentication, Authorization, and Access Control
Algorithm
An unambiguous formula or set of rules for solving a problem in a finite number of steps. Algorithms for encryption are usually called Ciphers.
APache eXtension Tool (apxs)
A perl script that aids in compiling module sources into Dynamic Shared Objects (DSOs) and helps install them in the Apache Web server.
See: Manual Page: apxs
Apache Portable Runtime (APR)
A set of libraries providing many of the basic interfaces between the server and the operating system. APR is developed parallel to the Apache HTTP Server as an independent project.
See: Apache Portable Runtime Project
Authentication
The positive identification of a network entity such as a server, a client, or a user.
See: Authentication, Authorization, and Access Control
Certificate
A data record used for authenticating network entities such as a server or a client. A certificate contains X.509 information pieces about its owner (called the subject) and the signing Certification Authority (called the issuer), plus the owner's public key and the signature made by the CA. Network entities verify these signatures using CA certificates.
See: SSL/TLS Encryption
Certificate Signing Request (CSR)
An unsigned certificate for submission to a Certification Authority, which signs it with the Private Key of their CA Certificate. Once the CSR is signed, it becomes a real certificate.
See: SSL/TLS Encryption
Certification Authority (CA)
A trusted third party whose purpose is to sign certificates for network entities it has authenticated using secure means. Other network entities can check the signature to verify that a CA has authenticated the bearer of a certificate.
See: SSL/TLS Encryption
Cipher
An algorithm or system for data encryption. Examples are DES, IDEA, RC4, etc.
See: SSL/TLS Encryption
Ciphertext
The result after Plaintext is passed through a Cipher.
See: SSL/TLS Encryption
Common Gateway Interface (CGI)
A standard definition for an interface between a web server and an external program that allows the external program to service requests. The interface was originally defined by NCSA but there is also an RFC project.
See: Dynamic Content with CGI
Configuration Directive
See: Directive
Configuration File
A text file containing Directives that control the configuration of Apache.
See: Configuration Files
CONNECT
An HTTP method for proxying raw data channels over HTTP. It can be used to encapsulate other protocols, such as the SSL protocol.
Context
An area in the configuration files where certain types of directives are allowed.
See: Terms Used to Describe Apache Directives
Digital Signature
An encrypted text block that validates a certificate or other file. A Certification Authority creates a signature by generating a hash of the Public Key embedded in a Certificate, then encrypting the hash with its own Private Key. Only the CA's public key can decrypt the signature, verifying that the CA has authenticated the network entity that owns the Certificate.
See: SSL/TLS Encryption
Directive
A configuration command that controls one or more aspects of Apache's behavior. Directives are placed in the Configuration File
See: Directive Index
Dynamic Shared Object (DSO)
Modules compiled separately from the Apache httpd binary that can be loaded on-demand.
See: Dynamic Shared Object Support
Environment Variable (env-variable)
Named variables managed by the operating system shell and used to store information and communicate between programs. Apache also contains internal variables that are referred to as environment variables, but are stored in internal Apache structures, rather than in the shell environment.
See: Environment Variables in Apache
Export-Crippled
Diminished in cryptographic strength (and security) in order to comply with the United States' Export Administration Regulations (EAR). Export-crippled cryptographic software is limited to a small key size, resulting in Ciphertext which usually can be decrypted by brute force.
See: SSL/TLS Encryption
Filter
A process that is applied to data that is sent or received by the server. Input filters process data sent by the client to the server, while output filters process documents on the server before they are sent to the client. For example, the INCLUDES output filter processes documents for Server Side Includes.
See: Filters
Fully-Qualified Domain-Name (FQDN)
The unique name of a network entity, consisting of a hostname and a domain name that can resolve to an IP address. For example, www is a hostname, example.com is a domain name, and www.example.com is a fully-qualified domain name.
Handler
An internal Apache representation of the action to be performed when a file is called. Generally, files have implicit handlers, based on the file type. Normally, all files are simply served by the server, but certain file types are "handled" separately. For example, the cgi-script handler designates files to be processed as CGIs.
See: Apache's Handler Use
Hash
A mathematical one-way, irreversable algorithm generating a string with fixed-length from another string of any length. Different input strings will usually produce different hashes (depending on the hash function).
Header
The part of the HTTP request and response that is sent before the actual content, and that contains meta-information describing the content.
.htaccess
A configuration file that is placed inside the web tree and applies configuration directives to the directory where it is placed and all sub-directories. Despite its name, this file can hold almost any type of directive, not just access-control directives.
See: Configuration Files
httpd.conf
The main Apache configuration file. The default location is /usr/local/apache2/conf/httpd.conf, but it may be moved using run-time or compile-time configuration.
See: Configuration Files
HyperText Transfer Protocol (HTTP)
The standard transmission protocol used on the World Wide Web. Apache implements version 1.1 of the protocol, referred to as HTTP/1.1 and defined by RFC 2616.
HTTPS
The HyperText Transfer Protocol (Secure), the standard encrypted communication mechanism on the World Wide Web. This is actually just HTTP over SSL.
See: SSL/TLS Encryption
Method
In the context of HTTP, an action to perform on a resource, specified on the request line by the client. Some of the methods available in HTTP are GET, POST, and PUT.
Message Digest
A hash of a message, which can be used to verify that the contents of the message have not been altered in transit.
See: SSL/TLS Encryption
MIME-type
A way to describe the kind of document being transmitted. Its name comes from that fact that its format is borrowed from the Multipurpose Internet Mail Extensions. It consists of a major type and a minor type, separated by a slash. Some examples are text/html, image/gif, and application/octet-stream. In HTTP, the MIME-type is transmitted in the Content-Type header.
See: mod_mime
Module
An independent part of a program. Much of Apache's functionality is contained in modules that you can choose to include or exclude. Modules that are compiled into the Apache httpd binary are called static modules, while modules that are stored separately and can be optionally loaded at run-time are called dynamic modules or DSOs. Modules that are included by default are called base modules. Many modules are available for Apache that are not distributed as part of the Apache HTTP Server tarball. These are referred to as third-party modules.
See: Module Index
Module Magic Number (MMN)
Module Magic Number is a constant defined in the Apache source code that is associated with binary compatibility of modules. It is changed when internal Apache structures, function calls and other significant parts of API change in such a way that binary compatibility cannot be guaranteed any more. On MMN change, all third party modules have to be at least recompiled, sometimes even slightly changed in order to work with the new version of Apache.
OpenSSL
The Open Source toolkit for SSL/TLS
See http://www.openssl.org/#
Pass Phrase
The word or phrase that protects private key files. It prevents unauthorized users from encrypting them. Usually it's just the secret encryption/decryption key used for Ciphers.
See: SSL/TLS Encryption
Plaintext
The unencrypted text.
Private Key
The secret key in a Public Key Cryptography system, used to decrypt incoming messages and sign outgoing ones.
See: SSL/TLS Encryption
Proxy
An intermediate server that sits between the client and the origin server. It accepts requests from clients, transmits those requests on to the origin server, and then returns the response from the origin server to the client. If several clients request the same content, the proxy can deliver that content from its cache, rather than requesting it from the origin server each time, thereby reducing response time.
See: mod_proxy
Public Key
The publicly available key in a Public Key Cryptography system, used to encrypt messages bound for its owner and to decrypt signatures made by its owner.
See: SSL/TLS Encryption
Public Key Cryptography
The study and application of asymmetric encryption systems, which use one key for encryption and another for decryption. A corresponding pair of such keys constitutes a key pair. Also called Asymmetric Cryptography.
See: SSL/TLS Encryption
Regular Expression (Regex)
A way of describing a pattern in text - for example, "all the words that begin with the letter A" or "every 10-digit phone number" or even "Every sentence with two commas in it, and no capital letter Q". Regular expressions are useful in Apache because they let you apply certain attributes against collections of files or resources in very flexible ways - for example, all .gif and .jpg files under any "images" directory could be written as "/images/.*(jpg|gif)$". Apache uses Perl Compatible Regular Expressions provided by the PCRE library.
Reverse Proxy
A proxy server that appears to the client as if it is an origin server. This is useful to hide the real origin server from the client for security reasons, or to load balance.
Secure Sockets Layer (SSL)
A protocol created by Netscape Communications Corporation for general communication authentication and encryption over TCP/IP networks. The most popular usage is HTTPS, i.e. the HyperText Transfer Protocol (HTTP) over SSL.
See: SSL/TLS Encryption
Server Side Includes (SSI)
A technique for embedding processing directives inside HTML files.
See: Introduction to Server Side Includes
Session
The context information of a communication in general.
SSLeay
The original SSL/TLS implementation library developed by Eric A. Young
Symmetric Cryptography
The study and application of Ciphers that use a single secret key for both encryption and decryption operations.
See: SSL/TLS Encryption
Tarball
A package of files gathered together using the tar utility. Apache distributions are stored in compressed tar archives or using pkzip.
Transport Layer Security (TLS)
The successor protocol to SSL, created by the Internet Engineering Task Force (IETF) for general communication authentication and encryption over TCP/IP networks. TLS version 1 and is nearly identical with SSL version 3.
See: SSL/TLS Encryption
Uniform Resource Locator (URL)
The name/address of a resource on the Internet. This is the common informal term for what is formally called a Uniform Resource Identifier. URLs are usually made up of a scheme, like http or https, a hostname, and a path. A URL for this page might be http://httpd.apache.org/docs/2.2/glossary.html.
Uniform Resource Identifier (URI)
A compact string of characters for identifying an abstract or physical resource. It is formally defined by RFC 2396. URIs used on the world-wide web are commonly referred to as URLs.
Virtual Hosting
Serving multiple websites using a single instance of Apache. IP virtual hosting differentiates between websites based on their IP address, while name-based virtual hosting uses only the name of the host and can therefore host many sites on the same IP address.
See: Apache Virtual Host documentation
X.509
An authentication certificate scheme recommended by the International Telecommunication Union (ITU-T) which is used for SSL/TLS authentication.
See: SSL/TLS Encryption
handler.html100644 0 0 20236 10422374001 10524 0ustar 0 0 Apache のハンドラの使用 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

Apache のハンドラの使用

Apache のハンドラの使用に関して記述しています。

top

ハンドラとは

「ハンドラ」とは、ファイルが呼ばれたときに実行される動作の Apache における内部表現です。 通常、ファイルはファイル型に基づいた暗黙のハンドラがあります。 普通はすべてのファイルは単にサーバに扱われますが、 ファイルタイプの中には別に「ハンドル」(訳注: 扱う) されるものもあります。

Apache 1.1 では、ハンドラを明示的に使用する機能が追加されました。 ファイルの拡張子や置いている場所に基づいて、 ファイル型と関係なくハンドラを指定することができます。 これはより優雅な解決法という点と、ファイルにタイプハンドラの両方を関連付けることができるという点で優れています。 (複数の拡張子のあるファイルも参照してください)。

ハンドラはサーバに組み込んだり、モジュールとして含めたり、 Action ディレクティブとして追加したりすることができます。 以下は標準配布に組み込まれているハンドラです。

top

CGI スクリプトを用いて静的なコンテンツを変更する

以下のディレクティブによって、拡張子が html であるファイルは footer.pl CGI スクリプトを起動するようになります。

Action add-footer /cgi-bin/footer.pl
AddHandler add-footer .html

CGI スクリプトは希望の修正や追加を行なって、元々要求された文書 (環境変数 PATH_TRANSLATED で指されています) を送る責任があります。

HTTP ヘッダのあるファイル

以下のディレクティブは send-as-is ハンドラを使用するように指示します。このハンドラは自分自身の HTTP ヘッダを持っているファイルに使用されます。ここでは、拡張子に関わらず、 /web/htdocs/asis ディレクトリにある全てのファイルは send-as-is ハンドラによって扱われます。

<Directory /web/htdocs/asis>
SetHandler send-as-is
</Directory>

top

プログラマ向けのメモ

ハンドラの機能を実装するために、利用すると便利かもしれないものが Apache API に追加されました。詳しく言うと、request_rec 構造体に新しいレコードが追加されたということです。

char *handler

もしモジュールがハンドラに関わりたい場合、 やらなければならないことは、リクエストが invoke_handler ステージに達する以前に r->handler を設定することだけです。ハンドラはコンテントタイプの代わりに ハンドラ名を使うようになっていること以外は、以前と同じように実装されています。 必ず要求されているわけではありませんが、メディアタイプ の名前空間を侵さないように、ハンドラの名前にはスラッシュを含まない、 ダッシュ (訳注: "-") で分離された名前を付ける習慣になっています。

howto/access.html100644 0 0 22510 10422374001 11505 0ustar 0 0 Access Control - Apache HTTP Server
<-
Apache > HTTP Server > Documentation > Version 2.2 > How-To / Tutorials

Access Control

Access control refers to any means of controlling access to any resource. This is separate from authentication and authorization.

top

Related Modules and Directives

Access control can be done by several different modules. The most important of these is mod_authz_host. Other modules discussed in this document include mod_setenvif and mod_rewrite.

top

Access control by host

If you wish to restrict access to portions of your site based on the host address of your visitors, this is most easily done using mod_authz_host.

The Allow and Deny directives let you allow and deny access based on the host name, or host address, of the machine requesting a document. The Order directive goes hand-in-hand with these two, and tells Apache in which order to apply the filters.

The usage of these directives is:

Allow from address

where address is an IP address (or a partial IP address) or a fully qualified domain name (or a partial domain name); you may provide multiple addresses or domain names, if desired.

For example, if you have someone spamming your message board, and you want to keep them out, you could do the following:

Deny from 10.252.46.165

Visitors coming from that address will not be able to see the content covered by this directive. If, instead, you have a machine name, rather than an IP address, you can use that.

Deny from host.example.com

And, if you'd like to block access from an entire domain, you can specify just part of an address or domain name:

Deny from 192.168.205
Deny from phishers.example.com moreidiots.example
Deny from ke

Using Order will let you be sure that you are actually restricting things to the group that you want to let in, by combining a Deny and an Allow directive:

Order deny,allow
Deny from all
Allow from dev.example.com

Listing just the Allow directive would not do what you want, because it will let folks from that host in, in addition to letting everyone in. What you want is to let only those folks in.

top

Access control by environment variable

mod_authz_host, in conjunction with mod_setenvif, can be used to restrict access to your website based on the value of arbitrary environment variables. This is done with the Allow from env= and Deny from env= syntax.

SetEnvIf User-Agent BadBot GoAway=1
Order allow,deny
Allow from all
Deny from env=GoAway

Warning:

Access control by User-Agent is an unreliable technique, since the User-Agent header can be set to anything at all, at the whim of the end user.

In the above example, the environment variable GoAway is set to 1 if the User-Agent matches the string BadBot. Then we deny access for any request when this variable is set. This blocks that particular user agent from the site.

An environment variable test can be negated using the =! syntax:

Allow from env=!GoAway

top

Access control with mod_rewrite

The [F] RewriteRule flag causes a 403 Forbidden response to be sent. Using this, you can deny access to a resource based on arbitrary criteria.

For example, if you wish to block access to a resource between 8pm and 6am, you can do this using mod_rewrite.

RewriteEngine On
RewriteCond %{TIME_HOUR} > 20 [OR]
RewriteCond %{TIME_HOUR} < 07
RewriteRule ^/fridge - [F]

This will return a 403 Forbidden response for any request after 8pm or before 7am. This technique can be used for any criteria that you wish to check. You can also redirect, or otherwise rewrite these requests, if that approach is preferred.

top

More information

You should also read the documentation for mod_auth_basic and mod_authz_host which contain some more information about how this all works. mod_authn_alias can also help in simplifying certain authentication configurations.

See the Authentication and Authorization howto.

howto/auth.html100644 0 0 47436 10422374001 11223 0ustar 0 0 認証、承認、アクセス制御 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > How-To / チュートリアル

認証、承認、アクセス制御

This translation may be out of date. Check the English version for recent changes.

「認証」とは、誰かが自分は誰であるかを主張した場合に、 それを確認するための全過程を指します。「承認」とは、 誰かが行きたい場所に行けるように、あるいは欲しい情報を 得ることができるようにするための全過程を指します。

top

関連するモジュールとディレクティブ

top

はじめに

もし機密の情報や、ごくごく少数グループの人向けの情報を ウェブサイトに置くのであれば、この文書に書かれている テクニックを使うことで、そのページを見ている人たちが 望みの人たちであることを確実にできるでしょう。

この文書では、多くの人が採用するであろう、 ウェブサイトの一部分を保護する「一般的な」 方法についてカバーしています。

top

準備

この文書で取り扱われるディレクティブは、 メインサーバ設定ファイル (普通は <Directory> セクション中) か、あるいはディレクトリ毎の設定ファイル (.htaccess ファイル) かで用います。

.htaccess ファイルを用いるのであれば、 これらのファイルに認証用のディレクティブを置けるように サーバの設定をしないといけないでしょう。これは AllowOverride ディレクティブで可能になります。 AllowOverride ディレクティブでは、ディレクトリ毎の設定ファイル中に置くことのできる ディレクティブを、もしあれば、指定します。

認証について話を進めているので、次のような AllowOverride ディレクティブが必要になるでしょう。

AllowOverride AuthConfig

そうでなく、メインサーバ設定ファイルの中に 直接置くのであれば、当然ながらそのファイルへの書き込み 権限を持っていなければならないでしょう。

また、どのファイルがどこに保存されているか知るために、 サーバのディレクトリ構造について少し知っておく 必要があるでしょう。 これはそんなに難しくないので、この文書中で ディレクトリ構造について知っておく必要がある場面では、 明らかになるようにします。

top

動作させる

では、サーバ上のあるディレクトリをパスワードで保護する 基本手順を示します。

パスワードファイルを作る必要があります。 このファイルは、ウェブからアクセスできる場所に 置くべきではありません。他の人がパスワードファイルを ダウンロードできないようにするためです。例えば、 /usr/local/apache/htdocs でドキュメントを 提供しているのであれば、パスワードファイルは /usr/local/apache/passwd などに置いた方が良いでしょう。

ファイルを作るためには、Apache 付属の htpasswd を使います。このコマンドは Apache をどこにインストールしようとも、 インストールディレクトリの bin ディレクトリ以下に置かれます。ファイルを作るには、次のように タイプしてください。

htpasswd -c /usr/local/apache/passwd/passwords rbowen

htpasswd は、パスワードを要求し、その後 確認のためにもう一度入力するように要求してきます。

# htpasswd -c /usr/local/apache/passwd/passwords rbowen
New password: mypassword
Re-type new password: mypassword
Adding password for user rbowen

もし htpasswd がパスの中に入っていない場合は、 もちろん、実行するためにプログラムまでのフルパスを タイプする必要があります。私のサーバであれば、 /usr/local/apache/bin/htpasswd にプログラムが置かれています。

次に、サーバがパスワードを要求するように設定して、 どのユーザがアクセスを許されているかをサーバに知らせなければ なりません。 httpd.conf を編集するか .htaccess ファイルを使用するかで 設定します。例えば、ディレクトリ /usr/local/apache/htdocs/secret を保護したい場合は、 /usr/local/apache/htdocs/secret/.htaccess か httpd.conf 中の <Directory /usr/local/apache/apache/htdocs/secret> セクションに 配置して、次のディレクティブを使うことができます。

AuthType Basic
AuthName "Restricted Files"
AuthUserFile /usr/local/apache/passwd/passwords
Require user rbowen

個々のディレクティブについて見てみましょう。 AuthType ディレクティブはどういう認証方法でユーザの認証を行うかを 選択します。最も一般的な方法は Basic で、これは mod_auth_basic で実装されています。しかしながら、 これは気を付けるべき重要なポイントなのですが、 Basic 認証はクライアントからサーバへ、 パスワードを暗号化せずに送ります。ですから、 この方法は特に機密性の高いデータに対しては用いるべきでは ありません。 Apache ではもう一つ別の認証方法: AuthType Digest をサポートしています。 この方法は mod_auth_digest で実装されていて、もっと安全です。 ごくごく最近のクライアントしか Digest 認証をサポートしていないようです。

AuthName ディレクティブでは、認証に使う Realm (訳注: 領域) を設定します。Realm は大きく分けて二つの機能を提供します。 一つ目は、クライアントがパスワードダイアログボックスの 一部としてユーザにこの情報をよく提示する、というものです。 二つ目には、クライアントが与えられた認証領域に対してどのパスワードを 送信すれば良いのかを決定するために使われる、という機能です。

例えば、"Restricted Files" 領域中で 一度認証されれば、同一サーバ上で "Restricted Files" Realm としてマークされたどんな領域でも、クライアントは 自動的に同じパスワードを使おうと試みます。 このおかげで、複数の制限領域に同じ realm を共有させて、 ユーザがパスワードを何度も要求される事態を 防ぐことができます。もちろん、セキュリティ上の理由から、 サーバのホスト名が変わればいつでも必ず、 クライアントは再びパスワードを尋ねる必要があります。

AuthUserFile ディレクティブは htpasswd で作った パスワードファイルへのパスを設定します。 ユーザ数が多い場合は、リクエスト毎のユーザの認証のための プレーンテキストの探索が非常に遅くなることがあります。 Apache ではユーザ情報を高速なデータベースファイルに 保管することもできます。 mod_authn_dbm モジュールが AuthDBMUserFile ディレクティブを提供します。これらのファイルは dbmmanage プログラムで作成したり操作したりできます。 Apache モジュールデータベース中にあるサードパーティー製の モジュールで、その他多くのタイプの認証オプションが 利用可能です。

最後に、Require ディレクティブが、サーバのこの領域にアクセスできるユーザを 指定することによって、プロセスの承認部分を提供します。 次のセクションでは、Require ディレクティブの様々な用法について述べます。

top

複数の人が入れるようにする

上記のディレクティブは、ただ一人 (具体的にはユーザ名 rbowen の誰か) がディレクトリに 入れるようにします。多くの場合は、複数の人が 入れるようにしたいでしょう。ここで AuthGroupFile の登場です。

もし複数の人が入れるようにしたいのであれば、 グループに属するユーザの一覧の入っている、グループ名のついた グループファイルを作る必要があります。このファイルの 書式はきわめて単純で、お好みのエディタで生成できます。 ファイルの中身は次のようなものです。

GroupName: rbowen dpitts sungo rshersey

一行にスペース区切りで、グループに所属するメンバーの 一覧をならべるだけです。

既に存在するパスワードファイルにユーザを加える場合は、 次のようにタイプしてください。

htpasswd /usr/local/apache/passwd/passwords dpitts

以前と同じ応答が返されますが、新しいファイルを 作るのではなく、既にあるファイルに追加されています。 (新しいパスワードファイルを作るには -c を使います。)

ここで次のようにして .htaccess ファイルを 修正する必要があります。

AuthType Basic
AuthName "By Invitation Only"
AuthUserFile /usr/local/apache/passwd/passwords
AuthGroupFile /usr/local/apache/passwd/groups
Require group GroupName

これで、グループ GroupName にリストされていて、 password ファイルにエントリがある人は、 正しいパスワードをタイプすれば入ることができるでしょう。

もっと特定せずに複数のユーザが入れるようにする、 もう一つの方法があります。グループファイルを作るのではなく、 次のディレクティブを使えばできます。

Require valid-user

require user rbowen 行でなく、上記を使うと、 パスワードファイルにリストされている人であれば誰でも 許可されます。 単にパスワードファイルをグループ毎に分けておくことで、 グループのような振る舞いをさせることもできます。 このアプローチの利点は、Apache は二つではなく、 ただ一つのファイルだけを検査すればよいという点です。 欠点は、たくさんのパスワードファイルを管理して、その中から AuthUserFile ディレクティブに正しいファイルを参照させなければならない点です。

top

起こりえる問題

Basic 認証が指定されている場合は、 サーバにドキュメントをリクエストする度に ユーザ名とパスワードを検査しなければなりません。 これは同じページ、ページにある全ての画像を リロードする場合であっても該当します (もし画像も保護されたディレクトリから来るのであれば) 。 予想される通り、これは動作を多少遅くします。 遅くなる程度はパスワードファイルの大きさと比例しますが、 これは、ファイルを開いてあなたの名前を発見するまで ユーザ名のリストを読まなければならないからです。 そして、ページがロードされる度にこれを行わなければ なりません。

結論としては、一つのパスワードファイルに置くことのできる ユーザ数には実質的な限界があります。 この限界はサーバマシンの性能に依存して変わりますが、 数百のエントリを越えたあたりから速度低下が見られると予期されています。 その時は他の認証方法を考慮に入れた方が良いでしょう。

top

もっと巧みに制御できない ?

ユーザ名とパスワードによる認証は認証の一つの方法に過ぎません。 しばしば誰であるかということとは違う何かに基づいて、 入れるようにしたくなることもあるでしょう。 例えばその人がどこから来ているかといったことです。

AllowDeny ディレクティブを使って、ドキュメントを要求してきたマシンの ホスト名やホストアドレスに基づいて許可不許可を制御できます。 Order ディレクティブはこの二つと連携して動作し、Apache にどの順番でフィルタを適用するかを知らせます。

これらのディレクティブの使い方は次のようになります。

Allow from address

ここで、address は IP アドレス (または IP アドレスの一部)、あるいは完全修飾ドメイン名 (またはドメイン名の一部) です。 必要であれば複数のアドレスやドメイン名を指定できます。

例えば、もし誰かが掲示板を攻撃していて、 その人を閉め出したいのであれば、 次のようにすることができます。

Deny from 205.252.46.165

このアドレスから来る人は、このディレクティブの範囲内の コンテンツを見ることができないません。もし IP アドレスの代わりにマシン名があれば、それを使えます。

Deny from host.example.com

ドメイン全体からのアクセスを防ぎたければ、 単にアドレスやドメイン名の一部を指定することができます。

Deny from 192.101.205
Deny from cyberthugs.com moreidiots.com
Deny from ke

Order を使うことで、 DenyAllow の組み合わせで 入っても良いグループが本当に確実に限定できているようにできます。

Order deny,allow
Deny from all
Allow from dev.example.com

Allow ディレクティブを単純に列挙するのでは望みの動作をしないでしょう。 なぜなら、全ての人が入れるということに加えて、 指定したホストからの人が入れるようにするからです。 やりたいことは、指定した人たちだけが入れるように することです。

top

追加情報

これら全てがどのように動作するかについて もっと多くの情報が書かれている mod_auth_basicmod_authz_host の文書も読むとよいでしょう。

howto/cgi.html100644 0 0 63335 10422374001 11020 0ustar 0 0 Apache Tutorial: CGI による動的コンテンツ - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > How-To / チュートリアル

Apache Tutorial: CGI による動的コンテンツ

This translation may be out of date. Check the English version for recent changes.
top

はじめに

CGI (Common Gateway Interface) は、ウェブサーバが コンテンツ生成をする外部プログラムと協調して動作するための方法を 定義しています。そのプログラムはしばしば CGI プログラムや CGI スクリプトと呼ばれます。CGI は、ウェブサイトに動的な コンテンツを置くための最も簡単で一般的な方法です。このドキュメントは、 Apache ウェブサーバで CGI を設定し、 CGI プログラムを書き始めるための入門書となるでしょう。

top

CGI を許可するように Apache を設定する

CGI プログラムを正しく動作させるには、CGI を許可するように Apache の設定を行う必要があります。 これを行なうための方法がいくつかあります。

ScriptAlias

ScriptAlias ディレクティブを使用して、 CGI プログラム用の特別な別ディレクトリを Apache に設定します。 Apache は、このディレクトリ中の全てのファイルを CGI プログラムであると仮定します。 そして、この特別なリソースがクライアントから要求されると、 そのプログラムの実行を試みます。

ScriptAlias ディレクティブは以下のように使用します:

ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/

デフォルト位置に Apache をインストールしたならば、 この例はデフォルト状態の httpd.conf 設定ファイルに含まれています。 ScriptAlias ディレクティブは、URL の前に付加するディレクトリを定義する Alias ディレクティブとかなり似ています。 AliasScriptAlias は通常、DocumentRoot ディレクトリ外のディレクトリのために使用されます。 AliasScriptAlias との差は、ScriptAlias が接頭辞で始まるすべての URL は CGI プログラムとみなされるという追加の意味を含んでいることです。 従って、上記の例では、/cgi-bin/ で始まるリソースへのあらゆるリクエストに対して、ディレクトリ /usr/local/apache2/cgi-bin/ から提供し、それらを CGI プログラムとして扱うよう Apache に示します。

例えば、URL http://www.example.com/cgi-bin/test.pl が要求された場合、Apache は ファイル /usr/local/apache2/cgi-bin/test.pl を実行し、その出力を返すことを試みます。 もちろん、ファイルが存在し、実行可能であり、決められた方法で出力を返します。 そうでなければ、Apache はエラーメッセージを返します。

ScriptAlias ディレクトリ外の CGI

CGI プログラムは、セキュリティ上の理由から ScriptAlias されたディレクトリに制限されることがしばしばあります。この方法により、 CGI プログラムを使用できるユーザを管理者が厳しく制御することができます。 しかしながら、適切なセキュリティ事前対策がとられるならば、CGI プログラムを任意のディレクトリで実行できないようにする理由はありません。 例えば、ユーザに UserDir ディレクティブで彼らのホームディレクトリ配下にウェブコンテンツを持たせたいとします。 もし、彼らが CGI プログラムを持つことを望んでいても、メインの cgi-bin ディレクトリへのアクセスができない場合、 CGI プログラムを実行することができる他の場所が必要になります。

任意のディレクトリで CGI の実行を許可するには二段階の設定が必要です。 まず、AddHandlerSetHandler ディレクティブによって cgi-script ハンドラが可能になっている必要があります。 次に、Options ディレクティブで ExecCGI が指定されていなければなりません。

CGI の実行を可能にするために Options を明示的に使用する

サーバのメインの設定ファイル中で Options ディレクティブを明示的に使用することで、特定のディレクトリ配下で CGI の実行を許可するように指定することができます:

<Directory /usr/local/apache2/htdocs/somedir>
Options +ExecCGI
</Directory>

上記ディレクティブは、CGI ファイルの実行を可能にするよう Apache に伝えます。また、どのファイルが CGI ファイルかを サーバに伝える必要があります。次の AddHandler ディレクティブの例では、cgi または pl を拡張子に持つすべてのファイルを CGI プログラムとしてみなすことをサーバに伝えます:

AddHandler cgi-script .cgi .pl

.htaccess ファイル

.htaccess チュートリアルhttpd.conf を変更できない場合にどうやって CGI プログラムを 使えるようにするかを説明しています。

User ディレクトリ

.cgi で終わるすべてのファイルに対して CGI プログラムの 実行を許可するには、以下の設定を使用できます。

<Directory /home/*/public_html>
Options +ExecCGI
AddHandler cgi-script .cgi
</Directory>

ユーザディレクトリの cgi-bin サブディレクトリの すべてのファイルを CGI プログラムとして指定したい場合には 以下のようなものを使います。

<Directory /home/*/public_html/cgi-bin>
Options ExecCGI
SetHandler cgi-script
</Directory>

top

CGI プログラムを書く

「通常の」プログラミングと CGI プログラミングの間には主に二つの違いがあります。

一つは、CGI プログラムのすべての出力には MIME-type ヘッダを付けなければなりません。 これはどのような種類のコンテンツを受け取っているかをクライアントに示す HTTP ヘッダです。ほとんどの場合では、次のように出力します:

Content-type: text/html

もう一つは、出力を HTML か、ブラウザが表示することができる何か他の形式にする必要があります。 大抵の場合は HTML でしょうが、GIF イメージや他の非 HTML コンテンツを出力する CGI プログラムを書くこともあるでしょう。

これら二点以外では、CGI プログラムを書くことは、 あなたが書いている他のプログラムとよく似ているでしょう。

最初の CGI プログラム

次に示すのは、ブラウザに 1 行印字する CGI プログラムの例です。以下を入力し、first.pl というファイルに保存し、それを cgi-bin ディレクトリに置いてください。

#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "Hello, World.";

Perl に精通していなくても、 何が起こるかを理解することはできるでしょう。1 行目は、 /usr/bin/perl で見つけられるインタプリタに このファイルを供給することでこのプログラムが実行されることを Apache に (シェル上で実行しようとしているならば、そのシェルに ) 示します。2 行目は、前述したとおり content-type の定義を印字します。 これには復帰改行の二つの組を後に付加します。 これにより、ヘッダの終りに空行が置かれ、HTTP ヘッダの終りとボディの始まりを示します。3 行目は、"Hello, World." という文字列を印字し、これで終りとなります。

好みのブラウザを開き、アドレス

http://www.example.com/cgi-bin/first.pl

あるいはファイルを置いたロケーションを指定すると、 Hello, World. という 1 行がブラウザウィンドに現れるでしょう。 それはあまりエキサイティングなことではありません。 しかし、これがうまく動けば、 他のどのようなものでも動かすことができるようになります。

top

しかし、まだ動かない !

ウェブから CGI プログラムへのアクセスを行なったとき、 ブラウザで見る可能性がある四つの基本的なことがあります:

CGI プログラムの出力
素晴らしい ! それはすべてがうまく動いたことを意味します。 出力が正常だけれども、ブラウザが正常に処理してくれない場合は、 正しい Content-Type を CGI プログラム内で セットしたかを確認してください。
CGI プログラムのソースコード、または "POST Method Not Allowed" というメッセージ
これは、CGI プログラムを処理できるよう Apache を適切に設定していなかったことを意味します。「CGI を許可するように Apache を設定する」の章を読み直し、 あなたが何を間違えたかを探してみてください。
メッセージが "Forbidden" で始まっている
これはパーミッションの問題ということを意味します。 Apache のエラーログと、後述の「ファイルのパーミッション」 の章をチェックしてください。
"Internal Server Error" というメッセージ
Apache のエラーログをチェックすると、"Premature end of script headers" というログが記録されていると思います。そして、おそらく CGI プログラムによって生成されたエラーメッセージも記録されているでしょう。 この場合、CGI プログラムが適切な HTTP ヘッダを出力できない原因を知るために、 以下の各章でチェックしてみてください。

ファイルのパーミッション

サーバはあなたの権限で実行されていないのを忘れないように。 つまり、起動するとき、サーバは特権をもたないユーザ - 通常 nobodywww の権限で実行されます。したがって、あなたが所有する ファイルを実行するには別のパーミッションが必要となります。 通常、nobody が実行するのに十分なパーミッションを与える方法は、 ファイルに誰でも実行可能とするパーミッションを与えることです:

chmod a+x first.pl

また、もしあなたのプログラムが他のファイルを読み書きするならば、 それらのファイルは、これが可能となる正しいパーミッション を持っている必要があります。

パス情報と環境

コマンドラインからプログラムを実行するとき、 意識しなくてもシェルに渡される情報があります。 例えば、参照するファイルのためにどこを検索したらよいかを シェルに伝える PATH があります。

プログラムが CGI プログラムとしてウェブサーバによって実行されるとき、 それは同じ PATH ではないかもしれません。 CGI プログラム内で呼び出すあらゆるプログラム (例えば、sendmail のようなもの) は、 フルパスで指定する必要があるでしょう。それにより、CGI プログラムを実行しようとしたとき、 シェルはそのようなプログラムを見つけることができます。

同様なことは、スクリプトのインタプリタ (しばしば perl) へのパスで、CGI プログラムの 1 行目に次のように示されます:

#!/usr/bin/perl

これがインタープリタへの実際のパスであることを確認しておきます。

また、CGI プログラムが他の環境変数に依存している場合は、その環境変数が Apache から渡されるようにする必要があります。

プログラムエラー

CGI プログラムが失敗するのは大抵、プログラム自身に問題がある場合です。 一度 CGI の使い方を理解し、前述の二つの誤りを犯していないならば、 まず間違いなくそうでしょう。ブラウザを使ってテストする前に まず確認することは、コマンドラインからプログラムが実行できることです。 例えば、以下を実行してみてください:

cd /usr/local/apache2/cgi-bin
./first.pl

(perl インタプリタは呼ばないでください。 シェルと Apache がスクリプトの最初の行の パス情報 を使って見つけます。)

最初にプログラムから出力されるのは Content-Type を含み、 後に空行の続く HTTP ヘッダでなければなりません。他のものが出力されている 場合は、Apache はこのプログラムをサーバ経由で実行しようとしたときには Premature end of script headers エラーを出力します。詳細は 上記の CGI プログラムを書く を読んでください。

エラーログ

エラーログは友達です。 全てのうまくいかないことは、エラーログにメッセージを生成します。 必ずそれを最初に見るべきです。 もし、あなたがウェブサイトを主催している場所が エラーログの参照を許していないならば、きっと他のサイトで主催するべきです。 エラーログの読み方を学ぶことで、ほとんど全ての問題が迅速に確認され、 迅速に解決されるということが分かるでしょう。

Suexec

suexec サポートプログラムは バーチャルホストやユーザのホームディレクトリの場所に依って CGI プログラムを違うユーザ権限の下で走らせることを可能にします。 Suexec の権限のチェックは非常に厳しく、それを満たさない場合は CGI プログラムが Premature end of script headers エラーで 実行されません。

suexec を使っているかどうかを調べためには apachectl -V を実行して、SUEXEC_BIN の場所を調べてください。 Apache がそこに suexec のバイナリを発見した場合は、suexec が 使用されます。

suexec を完全に理解していない限り、使うべきではありません。 suexec を無効にするには、SUEXEC_BIN から指されている suexec バイナリを削除 (か名前を変更) するだけです。 suexec を読んだ後で、まだそれを 使いたいのであれば、suexec -V を実行して suexec の ログファイルの位置を調べ、そのログファイルを使ってポリシー違反を 見つけてください。

top

裏で何が起こっているのか?

CGI プログラミングに習熟すると、 裏で起こっていることについて更に理解することの役に立ちます。 ブラウザとサーバがどのように相互通信するかについては特にそうです。 なぜなら、"Hello, World." を印字するプログラムを書くことはおおいに結構ですが、 それは特に有益ではありません。

環境変数

環境変数は、 あなたがコンピュータを使うときに辺りに存在している値です。 それらは、パス (コマンドをタイプしたときに実行する実際のファイルを探し出すところ)、 ユーザ名、端末型などのような便利なものです。 通常、普段使用している環境変数の完全なリストを調べるには、 コマンドプロンプトで env を入力します。

CGI の処理中、サーバとブラウザも環境変数を設定し、 それにより相互に通信することができるようになります。 その環境変数は、ブラウザタイプ (Netscape, IE, Lynx)、サーバタイプ (Apache, IIS, WebSite)、実行されている CGI プログラムの名前などです。

これらの変数は CGI プログラマが使用できます。 そして、それはクライアントとサーバの通信の話の半分です。 必要な変数の完全なリストは http://hoohoo.ncsa.uiuc.edu/cgi/env.html にあります。

以下の単純な Perl CGI プログラムは、渡される全ての環境変数を表示します。同様のプログラムは、 Apache ディストリビューションの cgi-bin ディレクトリに二つ含まれています。 いくつかの変数が必須であり、いくつかは任意であることに注意してください。 そして、公式のリストにはないいくつかの変数が表示されているかもしれません。 さらに、Apache はデフォルトで用意されている基本的なものに あなた自身の環境変数を加えるための、 多くの異なる方法を用意してします。

#!/usr/bin/perl
print "Content-type: text/html\n\n";
foreach $key (keys %ENV) {
print "$key --> $ENV{$key}<br>";
}

STDIN と STDOUT

サーバとクライアント間のもう一つの通信は、標準入力 (STDIN)と標準出力 (STDOUT) を通じて行なわれます。通常の文脈において、STDIN はキーボードやプログラムが動作するために与えられるファイルを意味し、 STDOUT は通常コンソールまたはスクリーンを意味します。

ウェブフォームから CGI プログラムへPOST したとき、フォームのデータは特別なフォーマットで束ねられ、 STDIN を通して、CGI プログラムに引き渡されます。 プログラムはデータがキーボード もしくはファイルから来ていたかのように処理することができます。

「特別なフォーマット」はとても単純です。フィールド名と値はイコール (=) で結ばれます。そして値の組はアンパサンド (&) で結ばれます。 スペース、アンパサンド、イコールのような面倒な文字は、 それらが動作を駄目にしないようにその文字に相当する 16 進に変換されます。 全データ文字列は、以下のようになります:

name=Rich%20Bowen&city=Lexington&state=KY&sidekick=Squirrel%20Monkey

時々、このような文字列が URL に付加されるのを見るでしょう。その場合、サーバは QUERY_STRING という環境変数にその文字列を入れます。それは GET リクエストと呼ばれます。 HTML フォームでは、データを渡すために GETPOST のどちらを使用するかを、FORM タグの METHOD 属性の設定で指定します。

CGI プログラムは、その文字列を役に立つ情報に分割する責任があります。 幸いにも、そのデータ処理を助けるライブラリやモジュールが存在します。 これらは、CGI プログラムの他の面でも同様に役に立ちます。

top

CGI モジュール/ライブラリ

CGI プログラムを書くとき、面倒な仕事の大部分をしてくれる コードライブラリまたはモジュールを使うことを検討すべきです。 これはエラーを減らし、早い開発につながります。

Perl で CGI プログラムを書いているなら、モジュールは CPAN で提供されています。 この目的のための最も普及しているモジュールは CGI.pm です。 CGI::Lite も検討しましょう。これは、ほとんどのプログラム において必要とするすべての機能の最小セットの実装です。

C で CGI プログラムを書いているなら、いろいろな オプションがあります。これらの内の一つは http://www.boutell.com/cgic/ で提供されている CGIC ライブラリです。

top

更なる情報

CGI に関する情報はウェブで数多く提供されています。CGI の問題については Usenet の comp.infosystems.www.authoring.cgi で、 他のユーザと論議することができます。HTML Writers Guide の -servers メーリングリストは、あなたの質問に回答してくれる偉大なリソースです。 http://www.hwg.org/lists/hwg-servers/ で更に多くを探し出すことができます。

そしてもちろん、おそらく CGI プログラムの動作に関する詳細の全てが記述されている CGI の仕様を読むべきです。オリジナルバージョンを NCSA で、アップデートされたドラフトを Common Gateway Interface RFC プロジェクトで参照することができます。

CGI の問題について、加わっているメーリングリストまたはニュース グループに質問を送るとき、起こったもの、起こってほしいこと、 実際に起こったことがどう違うか、使用しているサーバ、 CGI プログラムを記述している言語に関する十分な情報と、 可能であれば問題のコードを提供するようにしてください。 そうすることで、問題がより間単に見つかるようになります。

Apache のソースコードにおいて問題を発見したことを確信していない限り、 CGI の問題に関する質問を Apache バグデータベースに送るべきでない ことに注目してください。

howto/htaccess.html100644 0 0 50532 10422374001 12046 0ustar 0 0 Apache チュートリアル: .htaccess ファイル - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > How-To / チュートリアル

Apache チュートリアル: .htaccess ファイル

.htaccess ファイルはディレクトリ毎に設定を変更する方法を 提供します。

top

.htaccess ファイル

top

.htaccess ファイルとは何か/その使い方

.htaccess ファイル (「分散設定ファイル」) は ディレクトリ毎に設定を変更する方法を提供します。ディレクティブの 書かれたファイルをディレクトリに置くことで、そのディレクトリとその サブディレクトリすべてにディレクティブを適用させることができます。

注:

.htaccess ファイルを別の名前にしたい場合は、 AccessFileName ディレクティブを 使って変更することができます。例えば、そのファイルを .config という名前にしたい場合は、以下の設定をサーバ設定ファイルに入れることが できます:

AccessFileName .config

一般に、.htaccess ファイルの構文は 主設定ファイル と同じです。これらのファイルに書くことのできるディレクティブは AllowOverride ディレクティブにより決まります。 このディレクティブは、.htaccess ファイルに 書かれたディレクティブの中で、、 どのディレクティブが適用されるかをカテゴリー単位で指定します。 .htaccess に書くことのできるディレクティブであれば、 説明文書には「上書き」という項目があり、.htaccess に書くことができるように なるための AllowOverride の値が指定されています。

例えば、AddDefaultCharset ディレクティブの説明を 見ると、.htaccess ファイルでの使用が許可されていることが わかります。 (ディレクティブの概要の所にある「コンテキスト」と書かれている 行を見てください。) 上書きと書かれている行には FileInfo とあります。ですから、.htaccess 中の このディレクティブが有効になるためには、少なくとも AllowOverride FileInfo が設定されている必要があります。

例:

コンテキスト: サーバ設定ファイル,バーチャルホスト,ディレクトリ,.htaccess
上書き: FileInfo

あるディレクティブを .htaccess ファイルに書くことができるか どうかわからないときは、そのディレクティブの説明を探して、".htaccess" のための「コンテキスト」の行を調べてください。

top

いつ .htaccess ファイルを使う(使わない)か。

一般的に、サーバの主設定ファイルにアクセスできない場合を除いて、 .htaccess ファイルの使用は極力避けてください。 世の中には、例えば、ユーザ認証は常に .htaccess ファイルで 行なわなければならない、という誤解が広まっていますが、まったくそんなことは ありません。ユーザ認証の設定はサーバ主設定ファイルに書くことができ、 実際、その方がより良い設定方法です。

.htaccess ファイルはコンテンツ提供者がディレクトリ毎の 設定を行ないたいけれど、サーバシステムの root アクセス権限を持っていない という場合にのみ使うべきものです。サーバ管理者が頻繁に設定変更を行ないたくは ない、というときには個々のユーザが .htaccess ファイルを使って 自分で設定の変更を行なうことを許可した方が良いときもあるでしょう。 これは特に、ISP が複数のユーザのサイトを一つのマシンでホストしていて、 各ユーザが設定の変更をできるようにしたいようなときにあてはまります。

しかし、普通は可能であれば .htaccess ファイルの使用は 避けてください。.htaccess ファイルに書こうと考えるような すべての設定は、サーバの主設定ファイルの <Directory> セクションで同じように行なうことが できます。

.htaccess ファイルの使用を避ける理由は主に二つあります。

一つ目はサーバの性能の問題です。AllowOverride ディレクティブが .htaccess ファイルの設定を許可している場合は、Apache は 各ディレクトリで .htaccess ファイルを探します。 ですから、.htaccess ファイルを許可すると、実際に使用しているか どうかに関わらず、性能の低下を招くことになります! また、.htaccess ファイルは文書がリクエストされる度に読み込まれます。

さらに、Apache は適用すべきディレクティブを集めるために、すべての 上位のディレクトリの .htaccess ファイルを探す必要があることにも 注意してください。(ディレクティブが適用される方法を 参照してください。)ですから、/www/htdocs/example にある ファイルがリクエストされたときは、Apache は以下のファイルを調べます。

/.htaccess
/www/.htaccess
/www/htdocs/.htaccess
/www/htdocs/example/.htaccess

ですから、そのディレクトリのそれぞれのファイルへのアクセスに対して、 上の例のファイルがまったく存在しないときでも、追加のファイルシステムの アクセスが行なわれることになります。(これは、.htaccess/ に対して有効になっているときの場合で、普通はそうなって いないことに注意してください。)

二つ目はセキュリティです。ユーザにサーバの設定を変更することを 許可することになりますので、あなた自身が管理できない変更をされる 恐れがあります。ユーザにこの特権を与えるのが良いのかどうか、十分 検討してください。また、ユーザに与える権限が必要なものよりも少なすぎると、 余分な技術サポート報告を受け取るようになる可能性が高いことにも 注意してください。確実に、ユーザにどの程度の権限を与えたか明確に告げるように してください。AllowOverride に 何を設定したかということと、関連する文書を示すことで、 後々の混乱をぐっと減らすことが できます。

ところで、ディレクティブの書かれた .htaccess/www/htdocs/example に置くことと、同じディレクティブを 主サーバ設定の Directory セクション <Directory /www/htdocs/example> に書くことは 完全に等価です:

/www/htdocs/example.htaccess ファイル:

/www/htdocs/example の .htaccess ファイルの 内容

AddType text/example .exm

httpd.conf のセクション file

<Directory /www/htdocs/example>
AddType text/example .exm
</Directory>

しかし、この設定はサーバ設定ファイルに書いた方がパフォーマンスの 低下が少なくなります。ファイルがリクエストされる度に 読み込まれる代わりに、Apache の起動時に 1 回だけ読み込めば よくなるからです。

AllowOverride ディレクティブの 値を none に設定することで .htaccess ファイル の使用を完全に無効にすることができます。

AllowOverride None

top

ディレクティブの適用のされ方

.htaccess ファイルの設定ディレクティブは .htaccess ファイルの存在するディレクトリと、そのサブディレクトリすべてに適用されます。 しかし、上の階層のディレクトリにも .htaccess ファイルが 存在するかもしれないことを覚えておくことは大切です。ディレクティブは現れる 順番に適用されます。ですから、あるディレクトリの .htaccess は ディレクトリツリーのより上の階層の .htaccess ファイルの 設定を上書きするかもしれません。そして、その .htaccess も より上の階層で書かれたディレクティブを上書きしたり、主サーバ設定ファイル そのものの設定を上書きしたりしているかもしれません。

例:

ディレクトリ /www/htdocs/example1 に以下の内容の .htaccess ファイルがあります:

Options +ExecCGI

(注: .htaccess ファイルで "Options" ディレクティブが有効になるためには、 "AllowOverride Options" を有効にする必要があります。)

ディレクトリ /www/htdocs/example1/example2 には 以下のような .htaccess ファイルがあります:

Options Includes

二つめの .htaccess により、ディレクトリ /www/htdocs/example1/example2 では CGI の実行は 許可されません。これは、Options Includes のみが 効力を持ち、それがすべての以前の設定を上書きするからです。

メイン設定ファイルに対する .htaccess のマージ

As discussed in the documentation on Configuration Sections, .htaccess files can override the <Directory> sections for the corresponding directory, but will be overriden by other types of configuration sections from the main configuration files. This fact can be used to enforce certain configurations, even in the presence of a liberal AllowOverride setting. For example, to prevent script execution while allowing anything else to be set in .htaccess you can use:

セクションの設定 に記載されているように、.htaccess ファイルを使って <Directory> セクションの設定をディレクトリ毎に上書きできますが、 メイン設定ファイル中にある、他の種類の設定セクションによって さらに上書きされることもあります。 この特徴を使って、 AllowOverride で自由度の高い設定があったとしても、ある特定の設定が確実に 反映されるようにできます。例えば、CGI スクリプトの実行は 不許可に、かつ、.htaccess でその他の項目は 設定できるように、という場合は次のようにできます :

<Directory />
Allowoverride All
</Directory>

<Location />
Options +IncludesNoExec -ExecCGI
</Location>

top

認証の例

もし認証の方法を知るためにこの部分に直接来たのであれば、次のことを 知っておくことが重要です。よくある誤解に、パスワード認証を行なうためには .htaccess ファイルを使う必要がある、というものがあります。 これは正しくありません。主サーバ設定ファイルの <Directory> セクションに 認証用のディレクティブを書く方が推奨される方法で、.htaccess ファイルは主サーバ設定ファイルを変更できないときにのみ使用すべきです。 いつ .htaccess ファイルを使うべきで、いつ使うべきではないかに ついては を参照してください。

以上のことをふまえた上で、もし .htaccess の使用が まだ必要だと思う場合は、次のようなものが望みのことをしてくれるかも しれません。

.htaccess ファイルの内容:

AuthType Basic
AuthName "Password Required"
AuthUserFile /www/passwords/password.file
AuthGroupFile /www/passwords/group.file
Require Group admins

これらのディレクティブが有効になるためには、 AllowOverride AuthConfig が有効でなくてはならないことに 注意してください。

認証と承認については 認証チュートリアルを 参照してください。

top

SSI の例

もう一つの .htaccess ファイルのよくある利用法は 特定のディレクトリで SSI を有効にすることです。これは、望みのディレクトリの .htaccess ファイルに以下の設定ディレクティブを書くことで 達成できます:

Options +Includes
AddType text/html shtml
AddHandler server-parsed shtml

これらのディレクティブが有効になるためには、 AllowOverride OptionsAllowOverride FileInfo が有効になっている必要があることに注意してください。

よりまとまった SSI の説明は SSI チュートリアルを 参照してください。

top

CGI の例

最後に、特定のディレクトリで CGI プログラムの実行を許可したいことが あるでしょう。これは以下の設定で行なうことができます:

Options +ExecCGI
AddHandler cgi-script cgi pl

もしくは、あるディレクトリのすべてのファイルが CGI プログラムと みなされるようにしたいなら、以下の設定で実現することができます:

Options +ExecCGI
SetHandler cgi-script

これらのディレクティブが有効になるためには、 AllowOverride OptionsAllowOverride FileInfo が有効である必要があることに注意してください。

CGI プログラムと設定のよりまとまった説明は CGI チュートリアルを参照してください。

top

問題解決

設定ディレクティブを .htaccess ファイルに書いたけれども、 期待した効果が得られないときには、いくつかの原因が考えられます。

一番よくあることは、設定ディレクティブが考慮されるようには AllowOverride が設定されていない というものです。該当のファイルのスコープに AllowOverride None が設定されていないことを確認してください。これを調べるための良い方法は、 .htaccess ファイルにごみを書いて、リロードすることです。 サーバのエラーが生成されないときは、ほぼ確実に AllowOverride None が設定されている状態になっています。

そうではなく、文書をアクセスしようとしたときにエラーが発生している ときは、Apache のエラーログを調べてください。.htaccess ファイルで 使用されたディレクティブが許可されていない、ということを知らせている 可能性が高いです。または、構文の間違いがあることを述べているかもしれません。 その場合にはまずそれを修正する必要があります。

howto/index.html100644 0 0 11343 10422374001 11355 0ustar 0 0 How-To / チュートリアル - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2

How-To / チュートリアル

This translation may be out of date. Check the English version for recent changes.
top

How-To / チュートリアル

認証

認証とは、誰かが自分は誰であるかを名乗っているものを検証する 処理のことです。承認とは、誰かが望みの場所に辿り着けたり、 望みの情報を手に入れたりすることを許可する処理のことです。

参照: 認証、承認、アクセス制御

CGI による動的コンテンツ

CGI (Common Gateway Interface) はウェブサーバが外部のコンテンツ 生成プログラムとどのように相互動作をするかを定義します。 その外部プログラムは通常 CGI プログラムや CGI スクリプトと呼ばれます。 CGI はウェブサイトに動的なコンテンツを追加するための、 一番単純でよく使われている方法です。この文書は Apache ウェブサーバに CGI を設定し、CGI プログラムを書き始めるためのイントロダクションです。

参照: CGI: 動的コンテンツ

.htaccess ファイル

.htaccess ファイルはディレクトリ毎に設定を変更するための 方法を提供します。設定ディレクティブが書かれたファイルが、あるドキュメント ディレクトリに置かれると、ディレクティブはそのディレクトリと すべてのサブディレクトリに適用されます。

参照: .htaccess ファイル

Server Side Includes イントロダクション

SSI (Server Side Includes) は HTML ページ中に書かれるディレクティブで、 ページが送られる時にサーバにより評価されます。これにより、ページ全体を CGI プログラムで生成したり、他の動的な技術を使うことなく、既存の HTML ページに動的に生成された内容を付加することができます。

参照: Server Side Includes (SSI)

ユーザ毎のウェブディレクトリ

複数ユーザの存在するシステムでは、それぞれのユーザは UserDir ディレクティブを使うことによって ホームディレクトリ上にウェブサイトを作成することができます。 URL http://example.com/~username/ を訪れた人は ユーザ "username" のホームディレクトリの、UserDir ディレクティブで指定された サブディレクトリからコンテンツを得ることになります。

参照: ユーザウェブディレクトリ (public_html)

howto/public_html.html100644 0 0 17520 10422374001 12553 0ustar 0 0 ユーザ毎のウェブディレクトリ - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > How-To / チュートリアル

ユーザ毎のウェブディレクトリ

複数のユーザのいるシステムでは、UserDir ディレクティブを使って 各ユーザがホームディレクトリにウェブサイトを構築できるように設定することが 可能です。URL http://example.com/~username/ を訪れた人は "username" というユーザの UserDir ディレクティブで指定された サブディレクトリからコンテンツを得ることになります。

参照

top

ユーザ毎のウェブディレクトリ

top

UserDir を使ってファイルのパスを設定する

UserDir ディレクティブは ユーザ毎のコンテンツが読み込まれるディレクトリを指定します。 このディレクティブはいろいろ違った形式を取ることができます。

スラッシュで始まらないパスが与えられたときは、ユーザのホームディレクトリ からの相対パスとみなされます。次の設定があったときに:

UserDir public_html

URL http://example.com/~rbowen/file.html は パス /home/rbowen/public_html/file.html へ 変換されます。

パスがスラッシュで始まるときは、ディレクトリパスはそのパスに ユーザ名を加えたものからなります。次の設定のとき:

UserDir /var/html

URL http://example.com/~rbowen/file.html は パス /var/html/rbowen/file.html へ変換されます。

アスタリスク (*) を含むパスが指定されたときは、アスタリスクを ユーザ名で置換したものが使用されます。このような設定だと:

UserDir /var/www/*/docs

URL http://example.com/~rbowen/file.html は パス /var/www/rbowen/docs/file.html へ変換されます。

top

この機能を使用できるユーザを制限する

UserDir のドキュメントに示されている構文を使うことで、 どのユーザがこの機能を使うことができるかを制限することができます:

UserDir enabled
UserDir disabled root jro fish

上の設定は dissabled 文のユーザ以外のすべてのユーザに 対して UserDir の機能を有効にします。同様にして、以下のように 数名のユーザ以外に対してこの機能を無効にすることもできます:

UserDir disabled
UserDir enabled rbowen krietz

他の例は UserDir の説明を参照してください。

top

ユーザ毎の CGI ディレクトリ

それぞれのユーザに専用の cgi-bin ディレクトリを与えるために、 <Directory> を使ってユーザのホームディレクトリの指定された領域に対して CGI を有効に することができます。

<Directory /home/*/public_html/cgi-bin/>
Options ExecCGI
SetHandler cgi-script
</Directory>

そして、UserDirpublic_html に設定されていると仮定すると、 そのディレクトリの CGI プログラム example.cgi は以下の様に呼び出されることができます:

http://example.com/~rbowen/cgi-bin/example.cgi

top

ユーザによる設定変更を許可

ユーザに彼らのウェブ空間でのサーバの設定の変更を許可する場合、 ユーザは .htaccess ファイルを使って設定を変更する必要があります。 AllowOverride の値を ユーザが変更することを許可したいディレクティブに対して十分なものに 設定していることを確認してください。この機能がどのようにして動作しているか の詳細は .htaccess チュートリアル を読んで ください。

howto/ssi.html100644 0 0 53605 10422374001 11053 0ustar 0 0 Apache チュートリアル: Server Side Includes 入門 - Apache HTTP サーバ
<-
Apache > HTTP サーバ > ドキュメンテーション > バージョン 2.2 > How-To / チュートリアル

Apache チュートリアル: Server Side Includes 入門

サーバサイドインクルードによって、既存の HTML ドキュメントに動的なコンテンツを追加することができます。

top

はじめに

この記事は、通常は単に SSI と呼ばれる Server Side Includes を扱います。この記事においては、サーバでの SSI を許可するための設定と、 現在の HTML ページに動的なコンテンツを加えるためのいくつかの基本的な SSI 技術を紹介します。

記事の後半では、SSI ディレクティブで SSI と共に実行することができる条件文のような 幾分高度な事柄について述べています。

top

SSI とは ?

SSI (Server Side Includes) は、HTML ページ中に配置されるディレクティブであり、 サーバでページを提供する時に評価されます。SSI は、CGI プログラムやその他の動的な技術で全てのページを提供せずに、 動的に生成されたコンテンツを現在の HTML ページに加えます。

どういう場合に SSI を使い、どういう場合にプログラムで ページを完全に生成するかは、ページのうちどの程度が静的であり、 ページが提供されるたびに再計算する必要がどの程度あるかで通常は決定します。 SSI は現在時刻のような小さい情報を加えるにはうってつけの方法です。 しかし、そのページのほとんどの部分が提供時に生成される場合は、 他の方法を探す必要があります。

top

SSI を許可するためのサーバの設定

サーバで SSI を許可するには、httpd.conf ファイルまたは .htaccess ファイルに次のディレクティブを指定する必要があります:

Options +Includes

この指定は、ファイルを SSI ディレクティブで解析させることを許可するということを Apache に伝えます。ほとんどの設定ではお互いを上書きできる、複数の Options があることに 注意してください。おそらく、設定が最後に評価されることを 保証されるために、SSI を使用したいディレクトリに Options ディレクティブを適用する必要があるでしょう。

全てのファイルが SSI ディレクティブで解析されるというわけではありません。 どのファイルが解析されるかを Apache に伝える必要があります。 これを行なうには二つ方法があります。 次のディレクティブを使うことで、例えば .shtml のような特別なファイル拡張子を持つファイルを解析するよう Apache に伝えることができます:

AddType text/html .shtml
AddOutputFilter INCLUDES .shtml

この方法の欠点は、もし現在のページに SSI ディレクティブを加えたい場合、 それらのディレクティブが実行されるように .shtml 拡張子にするため、そのページの名前と、 そのページへの全てのリンクを変更しなければならないことです。

もう一つの方法は、XBitHack ディレクティブを使用することです:

XBitHack on

XBitHack は、ファイルの実行ビットが立っている場合、 SSI ディレクティブにより解析することを Apache に伝えます。 従って、SSI ディレクティブを現在のページに加えるためには、 ファイル名を変更しなくてもよく、単に chmod を使用してファイルを実行可能にするだけで済みます。

chmod +x pagename.html

行なうべきではないことに関する短いコメント。時々誰かが、全ての .html ファイルを SSI で解析するよう Apache に伝えれば、 わざわざ .shtml というファイル名にする必要がないといって 薦めるのを見ることでしょう。こういう人たちは、おそらく XBitHack について聞いたことがないのでしょう。 この方法について注意することは、たとえ SSI ディレクティブを全く含まない場合でも、Apache がクライアントに 送る全てのファイルを最後まで読み込ませることになります。 この方法はかなり処理を遅くするものであり、良くないアイデアです。

もちろん、Windows ではそのような実行ビットをセット するようなものはありませんのでオプションが少し制限されています。

デフォルトの設定では、Apache は SSI ページについて最終変更時刻や コンテンツの長さを HTTP ヘッダに送りません。 動的なコンテンツであるため、それらの値を計算するのが難しいからです。 このためドキュメントがキャッシュされなくなり、 結果としてクライアントの性能が遅くなったように感じさせることになります。 これを解決する方法が二つあります:

  1. XBitHack Full 設定を使用する。 この設定により、もともと要求されたファイルの時刻を参照し、 読み込まれるファイルの変更時刻を無視して最終変更時刻を決定するよう Apache に伝えます。
  2. mod_expires で提供されているディレクティブを使用して、 ファイルが無効になる時刻を明示します。これにより、 ブラウザとプロキシにキャッシュが有効であることを通知します。
top

基本的な SSI ディレクティブ

SSI ディレクティブは以下の文法で記述します:

<!--#element attribute=value attribute=value ... -->

HTML のコメントのような書式をしているので、もし SSI を正しく動作可能にしなければ、ブラウザはそれを無視するでしょう。 しかし、HTML ソース中では見えます。もし SSI を正しく設定したなら、 ディレクティブはその結果と置き換えられます。

element はたくさんあるものから一つ指定することができます。 指定できるものの大多数については、次回もう少し詳しく説明します。 ここでは、SSI で行なうことができる例をいくつか示します。

今日の日付

<!--#echo var="DATE_LOCAL" -->

echo 要素は単に変数の値を出力します。 CGI プログラムに利用可能な環境変数の全ての セットを含む多くの標準変数があります。また、set 要素を用いることで、独自の変数を定義することができます。

出力される日付の書式が好きではない場合、その書式を修正するために、 config 要素に timefmt 属性を使用することができます。

<!--#config timefmt="%A %B %d, %Y" -->
Today is <!--#echo var="DATE_LOCAL" -->

ファイルの変更日

This document last modified <!--#flastmod file="index.html" -->

この要素も timefmt フォーマットの設定に従います。

CGI プログラムの結果を取り込む

これは、全ての人のお気に入りである ``ヒットカウンタ'' のような CGI プログラムの結果を出力する SSI のより一般的な使用のうちの一つです。

<!--#include virtual="/cgi-bin/counter.pl" -->

top

追加の例

以下は、SSI を使用して HTML ドキュメントにおいてできることのいくつかの特別な例です。

いつこのドキュメントは修正されたのか ?

先に、ドキュメントが最後に変更されたのはいつかを ユーザに通知するために SSI を使用することができることを述べました。 しかしながら、実際の方法は、いくぶん問題のままにしておきました。 HTML ドキュメントに配置された次のコードは、ページにそのような タイムスタンプを入れるでしょう。もちろん、上述のように、 SSI を正しく動作可能にしておく必要があります。

<!--#config timefmt="%A %B %d, %Y" -->
This file last modified <!--#flastmod file="ssi.shtml" -->

もちろん、ssi.shtml の部分を実際の当該ファイル名と置き換える必要があります。 もし、あらゆるファイルに張ることができる一般的なコードを探しているなら、 これは不便であるかもしれません。おそらくその場合は、 そうする代わりに変数 LAST_MODIFIED を使用したいと考えるでしょう:

<!--#config timefmt="%D" -->
This file last modified <!--#echo var="LAST_MODIFIED" -->

timefmt 書式についてのより詳細については、お好みの検索サイトに行き、 strftime で検索してみてください。文法は同じです。

標準のフッタを挿入する

もし数ページを超えるページを持つサイトを管理しているならば、 全ページに対して変項を行なうことが本当に苦痛となり得ることが 分かるでしょう。全てのページに渡ってある種の標準的な外観を 維持しようとしているならば特にそうでしょう。

ヘッダやフッタ用の挿入用ファイルを使用することで、 このような更新にかかる負担を減らすことができます。 一つのフッタファイルを作成し、それを include SSI コマンドで各ページに入れるだけで済みます。include 要素は、file 属性または virtual 属性のいずれかを使用してどのファイルを挿入するかを決めることができます。 file 属性は、カレントディレクトリからの相対パスで示された ファイルパスです。 それは / で始まる絶対ファイルパスにはできず、また、そのパスの一部に ../ を含むことができないことを意味します。virtual 属性は、おそらくより便利だと思いますが、提供するドキュメントからの相対 URL で指定すべきです。それは / で始めることができますが、 提供するファイルと同じサーバ上に存在しなくてはなりません。

<!--#include virtual="/footer.html" -->

私は最後の二つを組み合わせて、LAST_MODIFIED ディレクティブをフッタファイルの中に置くことがよくあります。 SSI ディレクティブは、挿入用のファイルに含ませたり、 挿入ファイルのネストをしたりすることができます。すなわち、 挿入用のファイルは他のファイルを再帰的に挿入することができます。

top

他に何が設定できるのか ?

時刻書式を config で設定できることに加えて、 更に二つ config で設定することができます。

通常、SSI ディレクティブで何かがうまくいかないときは、 次のメッセージが出力されます。

[an error occurred while processing this directive]

このメッセージを他のものにしたい場合、config 要素の errmsg 属性で変更することができます:

<!--#config errmsg="[It appears that you don't know how to use SSI]" -->

おそらく、エンドユーザはこのメッセージを決して見ることはありません。 なぜなら、そのサイトが生きた状態になる前に SSI ディレクティブに関する 全ての問題を解決しているはずだからです。(そうですよね?)

そして、config において sizefmt 属性を使用することで、 返されるファイルサイズの書式を設定することができます。 バイト数には bytes を、適当に Kb や Mb に短縮させるには abbrev を指定することができます。

top

コマンドの実行

今後数ヶ月のうちに、小さな CGI プログラムと SSI を使用する記事を出したいと考えています。ここではそれとは別に、 exec 要素によって行なうことができることを示します。 SSI にシェル (正確には /bin/sh。Win32 ならば DOS シェル) を使用してコマンドを実行させることができます。 下記の例では、ディレクトリリスト出力を行ないます。

<pre>
<!--#exec cmd="ls" -->
</pre>

Windows 上では、

<pre>
<!--#exec cmd="dir" -->
</pre>

Windows 上では、このディレクティブによっていくつかの奇妙な 書式に気づくでしょう。なぜなら dir の出力が文字列 ``<dir>'' を含み、ブラウザを混乱させるからです。

この機能は非常に危険であり、どんなコードでも exec タグに埋め込まれてしまえば実行することに注意してください。例えば `` ゲストブック '' のように、もし、 ユーザがページの内容を編集できる状況にあるならば、 この機能を確実に抑制してください。Options ディレクティブの IncludesNOEXEC 引数を指定することで、 SSI は許可するけれど exec 機能は許可しないようにすることができます。

top

高度な SSI テクニック

コンテンツを出力することに加え、Apache SSI は変数を設定し、 そして比較と条件分岐にその変数を使用できる機能を提供しています。

警告

この記事で述べた大部分の機能は、Apache 1.2 以降を使用している場合のみ利用可能です。もちろん、もし Apache 1.2 以降を使用してない場合、直ちにアップグレードする必要があります。 さぁ、今それを行ないなさい。それまで待っています。

変数を設定する

set ディレクティブを使用して、 後で使用するために変数を設定することができます。 これは後の説明で必要になるので、ここでそれについて述べています。 文法は以下のとおりです:

<!--#set var="name" value="Rich" -->

このように単純に文字どおりに設定することに加え、 環境変数や上記の変数 (例えば LAST_MODIFIED のような) を含む他のあらゆる変数を値を設定するのに使用することができます。 変数名の前にドル記号 ($) を使用することで、 それがリテラル文字列ではなくて変数であることを示します。

<!--#set var="modified" value="$LAST_MODIFIED" -->

ドル記号 ($) を文字として変数の値に入れるには、 バックスラッシュによってドル記号をエスケープする必要があります。

<!--#set var="cost" value="\$100" -->

最後になりますが、長い文字列の中に変数を置きたい場合で、 変数名が他の文字とぶつかる可能性があり、 それらの文字について混乱してしまう場合、この混乱を取り除くため、 変数名を中括弧で囲むことができます (これについての良い例を示すのは難しいのですが、 おそらく分かっていただけるでしょう)。

<!--#set var="date" value="${DATE_LOCAL}_${DATE_GMT}" -->

条件式

さて、変数を持っていて、 それらの値を設定して比較することができるのですから、 条件を表すためにそれらを使用することができます。これにより SSI はある種の小さなプログラミング言語になっています。 mod_include は条件を表現するために if, elif, else, endif 構造を提供しています。これによって、 一つの実際のページから複数の論理ページを効果的に生成することができます。

条件構造は以下のとおりです:

<!--#if expr="test_condition" -->
<!--#elif expr="test_condition" -->
<!--#else -->
<!--#endif -->

test_condition はあらゆる種類の論理的比較をすることができます。 値を比較したり、その値が ``真'' かどうかを評価します (空でないなら与えられた文字列は真です)。 利用可能な比較演算子の全てのリストについては、 mod_include ドキュメンテーションを参照してください。 ここでは、この構造をどう使用するかの例をいくつか示します。

設定ファイルで次の行を記述します:

BrowserMatchNoCase macintosh Mac
BrowserMatchNoCase MSIE InternetExplorer

これはクライアントが Macintosh 上でインターネットエクスプローラが動いている場合、環境変数 ``Mac'' と ``InternetExplorer'' を真と設定します。

次に、SSI が可能になったドキュメントで以下を行ないます:

<!--#if expr="${Mac} && ${InternetExplorer}" -->
Apologetic text goes here
<!--#else -->
Cool JavaScript code goes here
<!--#endif -->

Mac 上の IE に対して何か思うところがあるわけでありません。 他では実行できているいくつかの JavaScript を Mac 上の IE で実行させるのに、先週数時間苦労したというだけのことです。 上の例はその暫定的な対処方法です。

他のどんな変数 (あなたが定義するもの、 または普通の環境変数のいずれか) も、条件文に使用することができます。 Apache は SetEnvIf ディレクティブや他の関連 ディレクティブを使用して環境変数を設定することができます。 この機能により、CGI に頼ることなくかなり複雑な動的なことをさせることができます。

top

終わりに

SSI は確かに CGI や動的なウェブページを生成する他の技術に代わるものではありません。 しかし、たくさんの余分な作業をせずに、 少量の動的なコンテンツを加えるにはすぐれた方法です。

images/caching_fig1.gif100644 0 0 40203 10422373543 12465 0ustar 0 0 GIF89aX  %&&+++&'(555469:::7894L(6H'>Y1;G>@B=CK4AQ,Fe3OpDDDEFHMMMNRXUUU]]]IOVIWhO^q]`eLb}ccdkkkgghimqoppssswxxIgLpSkPrOxQzLy~[xkefupXXYZ\`ycwkよaヴgfmkco淫u{tтspx~燕v印s懐{株z魚~厚〇サぇ旭幹慣減算雫傾ウ宮蛍警虎載及怨葛眼矩麹喰堅黒匙雌嘱倹激劫視巡冗杖据罩射シ未犀循述靭経興導省賛銚身運弌吹タ仙総戦走凋汀莫復折責惣義予青座乏倉監杙菟照埆勉局滷雪D覃矧母低‘鬘楓L濫劈偖吃甞雷枯藐磨盈饉呟経邉咄閣師鮃悍邪指団陳読読鉾杷癖僻版痛喨厘談嵶冱頒湮椀嗷嗷巉忤旡樛置詈宸幌貪壻宋霙暃竹翻麋燎巓穢溲槹穉熕楳癘籾宦閔璢档贅笏吩帶梟黨蝟樣窿粐肅肆裲跛粳黷鋺謗驤陂胛迹踉齠齟!,X H*\醗|#JH陰3j榿隠 CI欧(S\媛ニ0cI界8s袍紐@ J寒傳H*]粉哥PJJ紀妍Xj殃徽廸`K喬抒h唔]剖朷p稱K勲飮x鼕殍君濘 L鍵畸+^霧宴#KL慌緞3k滲g}驗K& &萢SwB 標'Ei0戡嵯o l僥蝦享OO`5c吮V.;c部Upw-Md R3F躬~貧O燔鵯WJ<}奇V[?\h`V BjcP× @ h`mV治 ; c PF=e?bhLsA Td`s~'p鈍礙2IqhXh2 ,m ソ{Sラ5蹴UeFa ?忿[BpFd`c経{c2n規1AnQNa~S?Vd.( dHz螽+丁螫;豁滲觚膊邨^鐓O諮餽GC賜循^霪O靡;<鰒n=S女o?_~赳~陞雹疹輜?o;hV@,`x@2 (AF0 t`慇j aGhA N%`WBr+!]XBNY' )H齢0}CΠ7 {( *qMbh#NA"氾衾`LU 鯑6搾pH:晢x味版> IBy;覇┬&$"3JZRQ$%1Ij$(EYO 趙&QSfT$Y KN &air%-sa2嗣%)ML]e, Li晰l6J頭&5yq^t.嫌pNq{版d敢~u&蜃H旆`u [u: Zt橿=涅z前':1r}T1[HOv哘b規-1z PtS@ `@b銭:1ヘvZ@M稀紵;屐Y菜続@ z裡J}>杞BKL9青-已2t給 #D(?楝選w遥變V -~@(Bj圻cg1)CBば@譟h鬟M`+Ow ~ @|W T\烝~ .~ダ@H_ETB忰f{" 措P @e<h(軟`PE9"g[(KQp穐e/$@8.d<&9u旡f(DNPhNI 凖.Y員%tl蝟#1EC`'a 係GA耋胯m0?}:4$JQ. @=h@ w -PデA 塑>RLC8瞰挑K1%=tzckE耿綻-o (X9$DAR蓄惘*&d迩岷&o`h{[Yh#D1nC $Z pw6篥5擢\;!于(NQ 5p<-8tWv]=茵qNo?朖w+AlT{>J x..仭 BB'`<嫐I,se愧!2G視N41jc`#芸+翻*WQ_  /OkBD} Nq!p櫛D聡.&`hOW顧67~[JK}c \ \[i~7-Fc fa7& 0zv8島鎔~zgS襁3f6yK&^a'eKdoxtA'v|!!" ppCa~tp __EeOw9 ` >G<墅@  Dj桾lTUQdeW槽dDzh\ofzqQ60b6S oC eSc9{F πq' AS q LVZt癜 c:}v jV ip@ Cpx`*嚼矢o C@\{eX5W^厳mphぐpH)qs#3wVqvo p 0 Hx|KF !!`p p`vO1cLdk6_4go6 pjj0|t駅`*寳)驥R lP[6h_8]SVAx ( :K85`,顰TRt]`u{ 6l]o :詒, w Whiu]原_L{PYq送_z ( 囎 `C!_0y7[Q_D  gzj HDi姆X_`P aczp0 G惇x!!PI^S)WgW0BeQw0tB(#t薈~KXaSc*MIE0狙]Gq}鉚[M_Rh)畳wu@ 遍?AVUW0h|Kp@ g P1i8 ` r@籰@Q^X_UwpV疊qX彦絵 俳x0F9QeWyh^GKwp @w yz卆j娠Y^8^R`ah @ '" 咒yy 1\%wvkCvQ X8l~J悒 P2 svj7f?XNg 意`R`^7k(n(ixo茱IUhX5_OeeP z懇E`*臉 p &W7HDXp: >w( dJ oC 彊0 ~dufyh"8| ├g2]_R& l(逧#勘P G 衾*qY@yev{ t0jぱH撚D双4髷vYwR `0魄zi"A[F7 ^ss'wrws'#[0 pτ慌kxywqp@ZwP| J9=S-@yp3b生%eqz擲无*wcdQgsv_+ L) |塢$飩e _h^cWv@ q* xD RY 7]Z{`至{#|yo+傘[ $U3L段P┿ c"Twk,qz江fjpo学Q xvk7Wsw^Qpu7e?kYquQ鰭|)湘nEqpvg自[V5ixik-e\t[( ;aQY| U^3{sr)Xiqぐ7卑&v^%藾 xHq4< p痴9W\V電f%SZ肆:HA  fpR犁!釟 _B|渥朞RO(p+`錬w8)紅*O`&杷v f^6噫{IK貉雹寮GLtz qq]w 紿藕嚼Zb0{ I0 z NE伉@m{Cw 宛 l u[\E秬e4'Bu,XX9a}h7+l-I {}:S` *79唸Нp茂&Y  : 鷹jP` KuH 0^=てX夂i9GYFKZ気 sF5 v^B|茴q`xQホk sP/p%砿樣鎚飩.払廾~pX}{f峙蓖c!コQWn袤ImL@ r@uPZ給P_Bhsz?uXck^OokZ) ;診XJQu員}  癒h0{N&s鞳HkQ憬鴾h$O xK (7P v:XIO鞜1_諺R=胃m+0穗批縷_i h$5任{WO_~>t1C!^顱D;VFD薇 E授_?yAb"B8hQ5Q{'Nh驛STUIaHYvjWj*);I RD.=p" ,*Zc 杯桝"PS^p趁1I髻4=A)斐 w$・//K3環e墹 (|(E2qUyY5踐:=&wx $?p*"(!5t_cK9Ynvz83=HBV3d-p$以@fG燦領vy毎*mG畑e00!匕lw覈.wuu.{k'}uR懈bS蜍.衲唄bE;1&r]%_辺鉛b鍋颱|N@銕s50翔+[申/[Hn> Z+:nrD圻Vx 丞qs壯9El9W0[J"a7尭3a8O s(0RBq B效u2B;A8="8bP)d腋:6mB\ q%nvI! `'UΦ謡e/u9?挿v*P7:殕+%5鍖hY#豢5M4mb7/1{8鶸署篥詳f#槙cR|2L帖-Zj#9\]h:噬3y|7b旁yef丞43冨n晨N鷄0懈 xI 秩V+委a癶"惜@ 癢>産Y能U吏y T/an技 j謠宍5S鎺]u>99暘|%?j,ryg?A B4Kr┬W<$^蛻-!H=ax/|<蒸}鰛q >( +>~;}l嬢廸\yzL,騒<〓fZ屐:[U B@9h?#*蝪~s7杰35m >p司C@59 s2BS@R.F@;I('o言R魎d-Q[Dc"?澪[&'@j醒1喘:>陀r`:"gLC+枩>痴 ?VA6C圜M<DT3cDB;9b@5"h諺3kZT U_Ads@1D$3Eb|7{Ba%TLdCIK<@AtBK=P-i c *U?n,EdG隋F‖!xK_$森c7>Gw沼\ ,F椎=}t~$8':涛MS?FTd4$xo闇jF鏖Q-dly漆/US]+$PJm麻OM]~K+S6UQSフ簓nU-h庵I-T 欒4/\T)Lu`="HV8 J3RV8Lg]q1zDV{|#悚#+,VJ4&{.D象%ZX\%X朔掘TXW/Cl車N卉BX企忖EdS+[穹_-YiOxyX,\+P鷦Xl~乞_U < /CQ孃][(!l杜5#w]9"0@0t \ut杳蟹?L負vU駝怐s渫]XFm∠ ご50楷瀉uU{X.j05劣1?7sZM漿吸縋酖(  =4:]渾?_ _QkRe[w)`=6%椀5@E秧u-mx\bl `%^Au紹l[-u.+//もM@uW)xsb斐b篆q0](xxc喚[y|42wYぼUq#aF226.-Hyェ (e@zwi)O9v@n@5)繝鼾-0-e普23,X9lQ cc(8Q eP2.wP~(4zg 3-y 3(V髓L^y!n漾V 2(2w8 P fcP *@5P2Pf0c.3x@Xjj( N3 ` .c.x52P,W嵜跌+@H0淒鞘]f}xz P (逢gm.ei(e0@bR20 02g0葦PxXk10j#deaF-m蟀BP1K.L^菲4f}@4~i.@孔kl*hil&d5@2@c (粥j@5:3Zk%t`aI葮>j栗-.: 壱wc60zKJ3 } j@de0 xvi┼ ?笈醴~j糟ZO`'vXoJm閖f8*:.4+ (}5 *0*傲+ #i0 Q?#z鈴f lyp  3>?収臈b}q$N逗X&~阯驫b q~H AW y@A'4 G @?E l S4|}qql槽$b"_;c \睨{誇kPW淺L7'鑄O O^o Z8CD$>厠W婢+Y0Swvpn便G+3]f矚Os-Zh厠寢C4RH!!mnVoM/,?P v)hk鷂煙w閣WZ (ヮy#d8訖@+ jHr") yj(i(c5 -+8茨w w`iL."ifZb_x Oく-~0 0pGjP5~沁i20jW  X3 y4(w(n乕(zPtP(>~T銹gedQ@h{ac 區{|g ~ nP~0{+2f凄Wx0p女 8 ~524Xw1u!m^}V(hP1 2lp!b$冰!7r跏#"GI-h%3謂~紗W預&!f,2,瓦⊂抖-D5: ┌4ごP<%`袖SA@)圖瓷+Y:R>Q 憊.}4`[asAA遐+lWUCx鬣W腫H効SAxqjP<莨 25nHDx2?)zqeQ@瓲Ik寛隰IKbJ[I X@P'_zj牀~5+SN'BHm)WI<`BM茘<{w伍{^互x;9?招S.y]wIsYgM1.>F'f豪;鐔;霑 ?<馘<竟τ@v;穿!柁>蕭疹 `v]R;LA腿{3_+`V< ╂2| #'HR`B! r/@j @EB, 8C雫BuCH圈%(^3:U mI(H碌C脆#.|G粒u$ sl_ QPW^  bKgUEoAR;錯F0$5Fq$Tp Vq 10(bhね*c1p p粥JB (A 收GM)DH!e92鉛#A*( a 殪/{y(/b^3#齟y>jRd7 5クP:孫}霖X2 ?v^Kc /qr$滓vXl(GQ8t#(''wLV沍C T〈]8H>"i╂S$ 3VI6{b E愧.