developer/ 40755 0 0 0 10423220656 10075 5 ustar 0 0 faq/ 40755 0 0 0 10423220656 6657 5 ustar 0 0 howto/ 40755 0 0 0 10423220656 7250 5 ustar 0 0 images/ 40755 0 0 0 10423220656 7355 5 ustar 0 0 misc/ 40755 0 0 0 10423220656 7043 5 ustar 0 0 mod/ 40755 0 0 0 10423220656 6667 5 ustar 0 0 platform/ 40755 0 0 0 10423220656 7734 5 ustar 0 0 programs/ 40755 0 0 0 10423220656 7742 5 ustar 0 0 rewrite/ 40755 0 0 0 10423220656 7571 5 ustar 0 0 ssl/ 40755 0 0 0 10423220656 6711 5 ustar 0 0 style/ 40755 0 0 0 10423220656 7250 5 ustar 0 0 style/_generated/ 40755 0 0 0 10423220656 11345 5 ustar 0 0 style/css/ 40755 0 0 0 10423220436 10034 5 ustar 0 0 style/lang/ 40755 0 0 0 10423220656 10171 5 ustar 0 0 style/latex/ 40755 0 0 0 10423220656 10365 5 ustar 0 0 style/xsl/ 40755 0 0 0 10423220656 10056 5 ustar 0 0 style/xsl/util/ 40755 0 0 0 10423220656 11033 5 ustar 0 0 vhosts/ 40755 0 0 0 10423220656 7436 5 ustar 0 0 bind.html 100644 0 0 22121 10423220655 10024 0 ustar 0 0
Apache HTTP サーバ バージョン 2.0

Apache が使用するアドレスとポートの設定をします。
| 関連モジュール | 関連ディレクティブ |
|---|---|
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
多くのプラットホームで IPv6 がサポートされてきていて、 APR はこれらのほとんどで IPv6 をサポートしているので、 Apache は IPv6 ソケットを割り当てて IPv6 経由で送られてきたリクエストを扱うことができます。
IPv6 ソケットが IPv4 と IPv6 コネクションの両方を扱うことができるか どうかは、Apache 管理者にとって厄介な問題です。 IPv4 コネクションを IPv6 ソケットで扱う場合は、 IPv4 マップされた IPv6 アドレスを使用していて、 ほとんどのプラットホームではデフォルトで使用可能ですが、 FreeBSD, NetBSD, OpenBSD では、システム全体としてのポリシーとの整合性から、 デフォルトでは使用不可に設定されています。 これらのデフォルトで使用不可のプラットホームであっても、 特別な設定パラメータで Apache の挙動を変化させることができます。
IPv4 と IPv6 のコネクションを最小限のソケットで扱いたいのであれば、
IPv4 マップの IPv6 アドレスを使用する必要があり、
--enable-v4-mapped configure オプションを指定して、単純に
Listen
ディレクティブで次のように設定します。
Listen 80
--enable-v4-mapped では、Apache
の生成するデフォルトの設定ファイル中の
Listen
ディレクティブはこの形式を使用しています。
--enable-v4-mapped は、
FreeBSD, NetBSD, OpenBSD 以外の全てのプラットホームでのデフォルトです。
ですから、おそらくお手元の Apache はこの設定でビルドされているでしょう。
プラットフォームや APR が何をサポートするかに関わらず、
IPv4 コネクションのみを扱うようにしたい場合は、
次の例のように全ての
Listen ディレクティブで
IPv4 アドレスを指定してください。
Listen 0.0.0.0:80
Listen 192.170.2.1:80
IPv4 と IPv6 のコネクションを個別のソケットで扱うようにしたい場合
(つまり IPv4 マップのアドレスを無効にしたい場合)
は、--disable-v4-mapped configure
オプションを指定して、次のように個別指定の
Listen
ディレクティブを使用してください。
Listen [::]:80
Listen 0.0.0.0:80
--disable-v4-mapped では、Apache
の生成するデフォルトの設定ファイル中の
Listen
ディレクティブはこの形式を使用しています。
--disable-v4-mapped は、
FreeBSD, NetBSD, OpenBSD プラットホームでのデフォルトです。
Listen でバーチャルホストが実装されるわけではありません。
Listen は単にメインサーバにどのアドレスとポートを listen すべきかを
教えるだけです。
<VirtualHost>
ディレクティブが使われない場合は、
受け入れたリクエストすべてに対して全く同じ挙動をします。
しかしながら
<VirtualHost>
を使って、
一つ以上のアドレスやポートに対して異なる挙動をするように
指定することができます。
VirtualHost を実装するには、使用するアドレスとポートを
まず初めにサーバに通知しなければなりません。
そして、その指定したアドレスとポートでの
このバーチャルホストの挙動を設定するために、
<VirtualHost>
セクションを作ります。もし
<VirtualHost>
が listen していないアドレスとポートに対して
設定されてしまうと、
それにはアクセスできないということに注意してください。
Apache HTTP サーバ バージョン 2.0

この文書では、Apache HTTP サーバを設定するのに使用するファイルについて 記述しています。
| 関連モジュール | 関連ディレクティブ |
|---|---|
Apache は ディレクティブ を設定ファイルに平文で書くことにより設定します。
メインの設定ファイルは普通は httpd.conf という名前です。
このファイルの位置はコンパイル時に設定されますが、コマンドラインの
-f フラグにより上書きできます。
また、他の設定ファイルを Include
ディレクティブによって追加でき、ワイルドカードを使用して多数の
設定ファイルを追加することができます。
どんなディレクティブも、これらの設定ファイルどれにでも入れることができます。
Apache は起動時か再起動時のみメイン設定ファイルの変更を認識します。
サーバは MIME
ドキュメントタイプを含んでいるファイルも読み込みます。ファイル名は
TypesConfig
で設定され、デフォルトでは mime.types
になっています。
Apache の設定ファイルは 1 行に 1 つのディレクティブからなります。 バックスラッシュ "\" はディレクティブが次の行に継続していることを 示すために行の最後の文字として使われているかもしれません。 行の最後とバックスラッシュの間に他の文字や空白があってはいけません。
設定ファイルのディレクティブは大文字小文字を区別しませんが、 引数にはしばしば区別するものがあります。ハッシュ文字 "#" で始まる行はコメントと見なされて無視されます。 設定ディレクティブの後の行ではコメントが含まれていてはいけません。ディレクティブの前の空行と空白は無視されますので、 わかりやすくするためにディレクティブをインデントしても構いません。
設定ファイルの構文エラーは、
apachectl configtest
かコマンドラインオプション
-t を使って調べられます。
| 関連モジュール | 関連ディレクティブ |
|---|---|
Apache はモジュール化されたサーバです。
コアサーバには最も基本的な機能だけが含まれています。拡張機能は
Apache にロードされるモジュールとして利用可能です。デフォルトでは、コンパイル時にモジュールの
Base セット (基本セット) が
サーバに含まれます。サーバが動的ロードモジュールを使うようにコンパイルされている場合は、
モジュールを別にコンパイルして、いつでも
LoadModule
ディレクティブを使って追加できます。
そうでない場合は、モジュールの追加や削除をするためには Apache
を再コンパイルする必要があります。設定ディレクティブは <IfModule>
ブロックに入れることで特定のモジュールが存在するときだけ
設定ファイルに含まれるようにすることができます。
コマンドラインオプション -l を使って現時点で
どのモジュールがサーバにコンパイルされているかを知ることができます。
| 関連モジュール | 関連ディレクティブ |
|---|---|
メイン設定ファイルにあるディレクティブはサーバ全体に適用されます。
サーバの一部分の設定だけを変更したい場合は <Directory>, <DirectoryMatch>, <Files>, <FilesMatch>, <Location>, <LocationMatch>
セクションの中に置くことで適用範囲を決められます。
これらのセクションはその中にあるディレクティブの適用範囲を
特定のファイルシステムの位置や URL に限定します。
非常に細粒度の設定を可能にするために、
セクションを入れ子にすることもできます。
Apache は同時に多くの違うウェブサイトを扱う能力があります。
これは バーチャルホスト と呼ばれています。
特定のウェブサイトにのみ適用されるようにするために、
ディレクティブは
<VirtualHost>
セクションの中に置くことでも適用範囲を変えることができます。
ほとんどのディレクティブはどのセクションにでも書けますが、 中にはコンテキストによっては意味をなさないものもあります。 例えば、プロセスの作成を制御しているディレクティブはメインサーバの コンテキストにのみ書くことができます。 どのディレクティブをどのセクションに書くことができるかを知るためには ディレクティブの コンテキスト を調べてください。詳しい情報は、 Directory, Location, Files セクションの動作法にあります。
| 関連モジュール | 関連ディレクティブ |
|---|---|
Apache ではウェブツリーの中に置かれた特別なファイルを使って
非中央集権的な設定管理をできます。その特別なファイルは普通は
.htaccess という名前で、
AccessFileName
ディレクティブでどんな名前にでも指定できます。
.htaccess
ファイルに書かれたディレクティブはファイルを置いた
ディレクトリとその全てのサブディレクトリに適用されます。
.htaccess
ファイルはすべてのリクエストで読み込まれるため、
変更はすぐに反映されます。
どのディレクティブが .htaccess
ファイルに書けるかを調べるには、ディレクティブのコンテキスト
を調べてください。サーバ管理者はさらにメイン設定ファイルの
AllowOverride
を設定することでどのディレクティブを .htaccess
ファイルに書けるようにするかを制御することができます。
.htaccess ファイルに関する詳しい情報は
.htaccess チュートリアル
を参照してください。
Apache HTTP サーバ バージョン 2.0

Apache は HTTP/1.1 の規格に記述されているコンテントネゴシエーションを サポートしています。 ブラウザにより提供されたメディアタイプ、 言語、文字セット、エンコーディングの優先傾向に基づいて、 最適なリソースの表現を選択できます。 また、不完全なネゴシエーション情報を送ってくるブラウザからのリクエストを もっと賢く取り扱えるよう、いくつか機能も実装してあります。
コンテントネゴシエーションは
mod_negotiation
モジュールによって提供されていて、デフォルトで組み込まれています。
リソースは、幾つか異なった表現で利用できる場合があります。 例えば、異なる言語や異なるメディアタイプ、 またはそれらの組み合わせで利用できるかも知れません。 もっとも適した選択をする方法の一つには、インデックスページを ユーザに見せて、ユーザに選んでもらう方法があります。 しかし、サーバが自動的に選ぶことができる場合が多くあります。 これは、ブラウザがリクエスト毎に、 どの表現を嗜好するかという情報を送ることで動作しています。 例えばブラウザは、可能ならフランス語で情報を見たい、 不可能ならその代わりに英語でもよいと、 自分の嗜好を知らせることができます。 ブラウザはリクエストのヘッダで自分の優先傾向を知らせます。 フランス語のみの表現を要求する場合は、ブラウザは次を送ります。
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 が異なる、 その状態を指して、 ネゴシエーションの次元と呼びます。
リソースをネゴシエーションするためには、 サーバは variant それぞれについての情報を知っておく必要があります。 これは以下の二つの方法のどちらかで行われます。
*.var ファイル)
を使う方法。 これは variant
を明示的に挙げているファイルを指定します。タイプマップは 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 はディレクトリ毎のオプションで、
httpd.confファイルの
<Directory>,
<Location>,
<Files>
セクション中や、(AllowOverride
が適切な値に 設定されていると) .htaccess
ファイルで Options
ディレクティブによって設定することができます。
Options All は
MultiViews
をセットしないことに注意してください。明示的に
その名前を書く必要があります。
MultiViews の効果は以下のようになります:
サーバが /some/dir/foo
へのリクエストを受け取り、/some/dir で
MultiViews が有効であって、
/some/dir/foo が存在しない場合、
サーバはディレクトリを読んで foo.*
にあてはまる全てのファイルを探し、
事実上それらのファイルをマップするタイプマップを作ります。
そのとき、メディアタイプとコンテントエンコーディングは、そのファイル名を
直接指定したときと同じものが割り当てられます。
それからクライアントの要求に一番合うものを選びます。
サーバがディレクトリの索引を作ろうとしている場合、
MultiViews
は DirectoryIndex
ディレクティブで指定されたファイルを探す過程にも
適用されます。設定ファイルに
DirectoryIndex index
が書かれていて、index.html と
index.html3 が
両方存在していると、サーバはその中からどちらかを適当に選びます。
もしその両方が存在せずに index.cgi
が存在していると、 サーバはそれを実行します。
もしディレクトリを読んでいる際に、
文字セット、コンテントタイプ、言語、エンコーディングを
指定するための mod_mime
で認識できる拡張子を持たないファイルが見つかると、結果は
MultiViewsMatch
ディレクティブの設定に依存します。このディレクティブは
ハンドラ、フィルタ、他のファイル拡張子タイプのどれが
MultiViews ネゴシエーションで使用できるかを決定します。
Apache はリソースの variant の一覧を、タイプマップファイルか ディレクトリ内のファイル名からかで取得した後、 「最適な」 variant を決定するために二つの方法の どちらかを起動します。 Apache のコンテントネゴシエーションの機能を使うために、 どのようにしてこの調停が行われるか詳細を知る必要はありません。 しかしながら、この文書の残りでは関心のある人のために、 使用されている方法について説明しています。
ネゴシエーション方法は二つあります。
| 次元 | 説明 |
|---|---|
| メディアタイプ | ブラウザは Accept
ヘッダフィールドで優先傾向を指定します。
アイテムそれぞれは、関連した品質数値を持つことができます。
variant の説明も品質数値を持つことができます
("qs" パラメータをご覧下さい)。 |
| 言語 | ブラウザは Accept-Language
ヘッダフィールドで優先傾向を指定します。
要素それぞれに品質数値を持たせることができます。
variants は 0 か 1 つかそれ以上の言語と
関連づけることができます。 |
| エンコーディング | ブラウザは Accept-Encoding
ヘッダフィールドで優先傾向を指定します。
要素それぞれに品質数値を持たせることができます。 |
| 文字セット | ブラウザは Accept-Charset
ヘッダフィールドで優先傾向を指定します。
要素それぞれに品質数値を持たせることができます。
variant はメディアタイプのパラメータとして文字セットを
指定することもできます。 |
ブラウザに返す「最適な」variant を (もしあれば) 選択するように Apache は次のアルゴリズムを使うことができます。 このアルゴリズムを設定により変更することはできません。 次のように動作します:
Accept
ヘッダの品質数値との積を計算して、最高値の variant
を選びます。Accept-Language ヘッダの言語順か、
(もしあれば)
LanguagePriority
ディレクティブの言語順で最適な言語の variant を選びます。Accept-Charset ヘッダ行で与えられている最高の文字セット
メディアパラメータを持つ variant を選びます。
明示的に除外されていない限り、ISO-8859-1
が許容されるようになっています。
text/* メディアタイプであるけれども
特定の文字セットに明示的に関連づけられているわけではない
variant は ISO-8859-1 であると仮定されます。Vary が設定されます
(リソースのキャッシュをする時に、
ブラウザやキャッシュはこの情報を使うことができます)。
以上で終わり。Vary ヘッダも設定されます。上記の 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-GB を en
にマッチします。
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
を選択しようとします。合致するものが無ければ、
通常のネゴシエーション手順が適用されます。
SetEnvIf Cookie "language=en" prefer-language=en
SetEnvIf Cookie "language=fr" prefer-language=fr
Apache は transparent content negotiation プロトコル
(RFC 2295) を次のように拡張しています。
特定のコンテントエンコーディングのみが利用可能である variant
に印を付けるために、新たに {encoding ..}
要素を variant リスト中に使っています。
リスト中のエンコードされた variant を認識し、
Accept-Encoding リクエストヘッダに従って許容される
エンコードをもった variant は、どれでも候補 variant
として使用するように、
RVSA/1.0 アルゴリズム (RFC 2296) の実装が拡張されました。
RVSA/1.0 の実装では、最適な variant が見つかるまで、
計算した品質数値は小数点以下 5 桁まで丸めません。
言語ネゴシエーションを使っている場合は、 ファイルが一つ以上の拡張子を持てて、 拡張子の順番は通常は考慮されない (詳細は 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)。
キャッシュが一つの表現を保存しているときは、 リクエスト URL と関連づけられています。 次にその URL がリクエストされた時に、キャッシュは 保存されている表現を使用できます。しかし、 リソースがサーバでネゴシエーション可能であれば、 最初のリクエストでキャッシュされて続くキャッシュヒットでは 間違った応答を返してしまうということになりかねません。 これを防ぐために、Apache はコンテントネゴシエーションの 後に返された応答全てに、HTTP/1.0 クライアントでは キャッシュ不可能の印をつけます。 また、ネゴシエーションされた応答のキャッシュを可能にする HTTP/1.1 プロトコルの機能も Apache はサポートします。
HTTP/1.0 準拠のクライアントからのリクエストに対しては、
(ブラウザであろうとキャッシュであろうと)
ネゴシエーションを受けた応答のキャッシュを許すために、
CacheNegotiatedDocs
ディレクティブを使用できます。
このディレクティブは、サーバ設定ファイルやバーチャルホストに書くことができ、
引数をとりません。
HTTP/1.1 クライアントからのリクエストには効力を持ちません。
コンテントネゴシエーションに関する追加情報は、 Alan J. Flavell さんのLanguage Negotiation Notes をご覧下さい。ですが、 Apache 2.0 での変更点を含むためには更新されていないかもしれない ということに注意してください。
Apache HTTP サーバ バージョン 2.0

ウェブマスターが何らかのエラーや問題に対する Apache の反応を設定できるようにする追加機能を提供します。
サーバがエラーや問題を発見した場合の反応を、 カスタマイズして定義することができます。
スクリプトの実行が失敗して "500 Server Error" を発生させたとします。この場合の反応を、より好ましいテキストや、別の URL (内部及び外部) へのリダイレクションに置き換えることができます。
NCSA httpd 1.3 は、古くて退屈なエラー/問題メッセージを 返していました。それはしばしばユーザには無意味であり、 またそれを発生させた原因を記録する方法も提供していませんでした。
するようにサーバを設定できます。
別の 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_URL と
REDIRECT_QUERY_STRING は新しい URL (CGI スクリプトか
CGI インクルードであると仮定されます) に渡されます。
他の変数は、エラーや問題が起きる前に存在した場合にだけ存在します。
もしあなたの設定した ErrorDocument が 外部リダイレクト
(すなわち、http:
のような体系名から始まるすべてのもの。たとえ同じホストを指していても)
ならば、これらはまったく設定されません。
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 (動作) は、
スクリプト/SSI に追加の環境変数が利用可能になるように、 リダイレクトされた URL に対する Apache の動作が変更されました。
リダイレクトされたスクリプトは標準の CGI 環境変数を利用可能でした。しかし、どこからリダイレクト されたかの情報は提供されていませんでした。
リダイレクトされた先のスクリプトが使用可能なように、
新しいたくさんの環境変数が初期化されます。新しい変数は、それぞれ
REDIRECT_ で始まります。
REDIRECT_ で始まる環境変数はリダイレクトされる前に存在していた
CGI 環境変数の頭に REDIRECT_ を付けて作成されます。
すなわち、HTTP_USER_AGENT は
REDIRECT_HTTP_USER_AGENT になります。
これらの新しい変数に加えて、Apache は、
スクリプトがリダイレクト元のトレースを助けるために
REDIRECT_URL と REDIRECT_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 のような
特定のエラーコンディションを扱うためだけに使われる場合は、
代わりに特定のコードとエラーテキストを使用することができます。
Apache HTTP Server Version 2.0

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:
We begin with an overview of the basic concepts behind the API, and how they are manifested in the code.
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:
SetEnv, which don't really fit well elsewhere.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:
OK.DECLINED. In this case, the server behaves in all
respects as if the handler simply hadn't been there.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.
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 */ };
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.
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 */
};
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:
*.var file), or a CGI script which returned a local
`Location:', then the resource which the user requested is going to be
ultimately located by some URI other than what the client originally
supplied. In this case, the server does an internal redirect,
constructing a new request_rec for the new URI, and
processing it almost exactly as if the client had requested the new URI
directly.ErrorDocument
is in scope, the same internal redirect machinery comes into play.Finally, a handler occasionally needs to investigate `what would happen if' some other request were run. For instance, the directory indexing module needs to know what MIME type would be assigned to a request for each directory entry, in order to figure out what icon to use.
Such handlers can construct a sub-request, using the
functions ap_sub_req_lookup_file,
ap_sub_req_lookup_uri, and ap_sub_req_method_uri;
these construct a new request_rec structure and processes it
as you would expect, up to but not including the point of actually sending
a response. (These functions skip over the access checks if the
sub-request is for a file in the same directory as the original
request).
(Server-side includes work by building sub-requests and then actually
invoking the response handler for them, via the function
ap_run_sub_req).
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
OK -- the request was handled successfully. This may or
may not terminate the phase.DECLINED -- no erroneous condition exists, but the module
declines to handle the phase; the server tries to find another.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.
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).
Stuff that should be discussed here in detail:
ap_auth_type,
ap_auth_name, and ap_requires.ap_get_basic_auth_pw, which sets the
connection->user structure field
automatically, and ap_note_basic_auth_failure,
which arranges for the proper WWW-Authenticate:
header to be sent back).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).
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.
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).
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".
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_poolpconfptemppchildptransr->poolFor 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.
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).
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.
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).
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.
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.
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:
(void *) pointer, which is passed in the
cmd_parms structure to the command handler ---
this is useful in case many similar commands are handled by
the same function.AllowOverride option, and an additional mask
bit, RSRC_CONF, indicating that the command may
appear in the server's own config files, but not in
any .htaccess file.TAKE2 indicates two pre-parsed arguments. Other
options are TAKE1, which indicates one
pre-parsed argument, FLAG, which indicates that
the argument should be On or Off,
and is passed in as a boolean flag, RAW_ARGS,
which causes the server to give the command the raw, unparsed
arguments (everything but the command name itself). There is
also ITERATE, which means that the handler looks
the same as TAKE1, but that if multiple
arguments are present, it should be called multiple times,
and finally ITERATE2, which indicates that the
command handler looks like a TAKE2, but if more
arguments are present, then it should be called multiple
times, holding the first argument constant.NULL).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;
}
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;
}
Apache HTTP Server Version 2.0

The allocation mechanism's 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.
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() 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.
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.
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.
This requires a bit of an understanding of how alloc.c works.
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 | - | No | Yes | Yes | Yes |
| ALLOC USE MALLOC | No | - | No | No | No |
| POOL DEBUG | Yes | No | - | Yes | Yes |
| MAKE TABLE PROFILE | Yes | No | Yes | - | Yes |
| ALLOC STATS | Yes | No | Yes | Yes | - |
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.
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.
In order to use the various options the server must be rebuilt after editing the header file.
Apache HTTP Server Version 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.
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 > 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" -> "gum"
* "/foo/bar/gum/" -> ""
* "gum" -> "gum"
* "wi\\n32\\stuff" -> "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.
Apache HTTP Server Version 2.0

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.
There are three basic filter types (each of these is actually broken down into two categories, but that comes later).
CONNECTIONAP_FTYPE_CONNECTION, AP_FTYPE_NETWORK)PROTOCOLAP_FTYPE_PROTOCOL,
AP_FTYPE_TRANSCODE)RESOURCEPROTOCOL, 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:
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.
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.
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.
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.
Apache HTTP Server Version 2.0

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.
In order to create a new hook, four things need to be done:
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.
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)
...
)
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().
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);
}
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.
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);
A module that wants a hook to be called needs to do two things.
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;
}
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, HOOK_MIDDLE);
}
mode MODULE_VAR_EXPORT my_module =
{
...
my_register_hooks /* register hooks */
};
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: HOOK_FIRST,
HOOK_MIDDLE and HOOK_LAST.
All modules using any particular value may be run in any
order relative to each other, but, of course, all modules using
HOOK_FIRST will be run before HOOK_MIDDLE
which are before HOOK_LAST. Modules that don't care
when they are run should use HOOK_MIDDLE. (I spaced
these out so people could do stuff like HOOK_FIRST-2
to get in slightly earlier, but is this wise? - Ben)
Note that there are two more values,
HOOK_REALLY_FIRST and 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, HOOK_MIDDLE);
}
Note that the sort used to achieve this is stable, so
ordering set by HOOK_ORDER is preserved, as far
as is possible.
Ben Laurie, 15th August 1999
Apache HTTP Server Version 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.
Apache HTTP サーバ バージョン 2.0

この文書は mod_mmap_static モジュールを Apache 2.0 用に移植した時に
学んだ経験をもとに書いた、最初の手引き書です。まだまだ完全じゃないし、
ひょっとすると間違っている部分もあるかもしれませんが、
取っ掛りにはなるでしょう。
クリーンナップルーチンは apr_status_t 型である必要があります。
そして、apr_status_t 型の値を返さなくてはなりません。
クリーンナップ中のエラーを通知する必要がなければ、返り値は普通、
ARP_SUCCESS です。たとえエラーを通知したとしても、
すべてのコードがその通知をチェックしたり、
エラーに応じた動作をするわけではないことに気をつけてください。
初期化ルーチンは処理全体から見てしっくりくるような意味を表すように、
名前が変更されました。ですから、mmap_init から mmap_post_config
のようにちょっと変更されました。
渡される引数は大幅に変更され、次のようになりました。
apr_pool_t *papr_pool_t *plogapr_pool_t *ptempserver_rec *sデータ型のほとんどは APR に移されました。つまり、 いくつかの名前が前述のように変更されています。 施すべき変更点の簡単な一覧を以下に示します。
pool becomes apr_pool_ttable becomes apr_table_t新しいアーキテクチャでは作成した関数を呼び出すのに
一連のフックを使用します。このフックは、新しい関数
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);
三つの位置が定義されています…
HOOK_FIRSTHOOK_MIDDLEHOOK_LAST位置を定義するには、上記の「位置」を指定し、 修飾子である「先行」と「後行」で手を加えます。 「先行」「後行」は、呼ばれるべき関数のリストです。 「先行」は関数の実行前に呼ばれるもので、 「後行」は実行後に呼ばれるものです。
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_methodap_hook_open_logsap_hook_auth_checkerap_hook_access_checkerap_hook_check_user_idap_hook_default_portap_hook_pre_connectionap_hook_process_connectionap_hook_child_initap_hook_create_requestap_hook_fixupsap_hook_handlerap_hook_header_parserap_hook_insert_filterap_hook_log_transactionap_hook_optional_fn_retrieveap_hook_post_read_requestap_hook_quick_handlerap_hook_translate_nameap_hook_type_checkerApache HTTP Server Version 2.0

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.
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.)
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.
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.
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.
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.
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.
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.
The main request then parses the client's headers. This prepares the remaining request processing steps to better serve the client's request.
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;
}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.
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.
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.
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.
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.
Apache HTTP Server Version 2.0

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.
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.
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.
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.
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.
Please drop a note to dev@httpd.apache.org if you have additions or corrections to this list.
| Library | Version | Thread 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. |
Apache HTTP サーバ バージョン 2.0

本文書の内容は次の一言に尽きます。「Apache が設定ファイルを読み込むときに DNS を使用する必要がないようにして下さい」。Apache が設定ファイルを 読み込むときに DNS を使用する必要がある場合、信頼性の問題 (起動しないかもしれません) やサービス拒否や盗用アタック (他のユーザからヒットを盗むことを含みます) の問題に直面するかもしれません。
<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>
サービス拒否が起こる場合、(少なくとも) 二つのケースがあります。
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 がどのように整合性を確保するかについて、
深い議論が必要になります。おおざっぱな説明はこちらに記述されています。
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 で調べると良いでしょう。
VirtualHost
で IP アドレスを使用する。
Listen
で IP アドレスを使用する。
ServerName
を持つようにする。
<VirtualHost _default_:*>
サーバを作る。DNS に関して、現状は全く宜しくありません。Apache 1.2 で、 DNS のイベントが失敗しても少なくとも起動プロセスが続くようにしましたが、 これが最高の解決方法ではないでしょう。アドレスの再割り当てが必要不可避 となっている今日のインターネットにおいては、 設定ファイルの中で明示的な IP アドレスを要求する仕様は、 全く宜しくありません。
盗用のサービスアタックに関して行なうべき事は、 DNS 順引きを行なって得られたアドレスに対する DNS 逆引きを行なって、二つの名前を比較することです。 この二つが一致しなければバーチャルホストは無効になるようにします。 こうするためには逆引き DNS が適切に設定されている必要があります (FTP サーバや TCP ラッパーのおかげで「二重逆引き」DNS は一般的に なっていますので、管理者にはお馴染みものでしょう)。
IP アドレスが使用されていなくて DNS が失敗した場合は、 どうしてもバーチャルホストウェブサーバを信頼性を確保して 起動させることは不可能のようです。 設定の一部を無効にするというような部分的な解決では、 サーバが何をするようにするかにもよりますが、 そのサーバが起動しないより確実に悪い状況になるでしょう。
HTTP/1.1 が開発され、ブラウザやプロキシが Host
ヘッダを発行するようになったので、IP ベースのバーチャルホストを
全く使用しなくても済むようになるかもしれません。
この場合、ウェブサーバは設定中に DNS 参照をしなくても済みます。
しかし 1997 年 3 月時点の状況では、
商用レベルのウェブサーバで使用できるほどには、
これらの機能は広く開発が進んでいません。
Apache HTTP サーバ バージョン 2.0

Apache HTTP サーバはモジュール化されたプログラムで、
管理者がモジュールを選択することでサーバに組み込む機能を選ぶことができます。
モジュールはサーバがビルドされるときに httpd バイナリに
静的に組み込むことができます。もしくは、httpd バイナリとは
別に存在する動的共有オブジェクト (訳注: Dynamic Shared Object)
(DSO) としてコンパイルすることも
できます。DSO モジュールはサーバがビルドされるときにコンパイルしたり、
Apache 拡張ツール (apxs) を
使って後でコンパイルして追加したりできます。
この文書は DSO モジュールの使い方と、仕組みについて 説明します。
| 関連モジュール | 関連ディレクティブ |
|---|---|
個々の Apache モジュールをロードするための DSO サポートは
mod_so.c というモジュールの機能に基づいています。
このモジュール は Apache のコアに静的に組み込まれている必要があります。
それは core.c 以外では DSO にできない唯一の
モジュールです。事実上、他のすべての Apache のモジュールは、
インストールの文書で説明されているように、
configure の
--enable-module=shared オプションでそれぞれを
DSO ビルドにすることにより、DSO モジュールにすることができます。
mod_foo.so のような DSO にモジュールがコンパイルされれば、
httpd.conf ファイル中で mod_so の
LoadModule
ディレクティブを使うことでサーバの起動や再起動時にこのモジュールを
ロードするようにできます。
Apache モジュール用の (特にサードパーティモジュールの) DSO ファイルの
作成を簡単にするために、apxs
(APache eXtenSion) という新しいサポートプログラムがあります。
Apache のソースツリーの外で DSO モジュールをビルドするために
使うことができます。発想は単純です: Apache のインストール時の
configure、make install のときに Apache の
C ヘッダをインストールし、DSO ビルド用のプラットフォーム依存の
コンパイラとリンカのフラグを apxs プログラムに追加します。
これにより、ユーザが Apache の配布ソースツリーなしで、さらに
DSO サポートのためのプラットフォーム依存のコンパイラやリンカの
フラグをいじることなく Apache のモジュールのソースをコンパイル
できるようになります。
Apache 2.0 の DSO 機能の概略を知ることができるための、 短く簡潔な概要です:
mod_foo.c
として、それを DSO mod_foo.so にビルド、インストール:
$ ./configure --prefix=/path/to/install --enable-foo=shared
$ make install
mod_foo.c
として、それを DSO mod_foo.so にビルド、インストール:
$ ./configure --add-module=module_type:/path/to/3rdparty/mod_foo.c --enable-foo=shared
$ make install
$ ./configure --enable-so
$ make install
mod_foo.c
として、それを apxs を使って
Apache ソースツリーの外で DSO にビルド、インストール:
$ cd /path/to/3rdparty
$ apxs -c mod_foo.c
$ apxs -i -a -n foo mod_foo.la
どの場合においても、共有モジュールをコンパイルした後で、
httpd.conf で
LoadModule
ディレクティブを使って Apache がモジュールを使用するように
しなければなりません。
最近の Unix 系の OS には 動的共有オブジェクト (DSO) の動的リンク/ロードという気のきいた機構が 存在します。これは、実行時にプログラムのアドレス空間に ロードできるような特別な形式でプログラムをビルドすることを 可能にします。
このロードは二つの方法で行なうことができます: 実行プログラムが
起動されたときに ld.so というシステムプログラム
により自動的に行なわれる方法と、実行プログラム中から、システムコール
dlopen()/dlsym() による Unix ローダへの
プログラムシステムのインタフェースを使って手動で行なう方法とが
あります。
最初の方法では DSO は普通は共有ライブラリや DSO
ライブラリ と呼ばれていて、DSO の名前は
libfoo.so や libfoo.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 を使ってモジュールをロードするようにすでに 運命付けられていたのです。
上記の DSO に基づいた機能は以下の利点があります:
configure のオプションを使う代わりに
実行時に httpd.conf の設定用コマンド
LoadModule
を使うことができますので、サーバパッケージの柔軟性が高まりました。
たとえば、一つの Apache のインストールから
違う構成のサーバ (標準版と SSL 版、最小構成と拡張版 [mod_perl, PHP3]
など) を実行することができます。apxs の組み合わせにより、Apache ソースツリーの
外で作業でき、開発中のモジュールの新しいバージョンを
実行中の Apache サーバに組み込むために apxs -i と
apachectl restart を行なうだけで良くなるからです。DSO には以下の欠点があります:
ld -lfoo)
というわけではありませんので (たとえば、a.out のプラットフォームでは
この機能はありませんが、ELF のプラットフォームにはあります)、
すべての種類のモジュールに DSO 機構を使えるわけではありません。
言い換えると、DSO ファイルとしてコンパイルされたモジュールの
使えるシンボルは、
Apache のコアのシンボル、C ライブラリ (libc) と
Apache コアが使っている他のすべての静的なライブラリと動的ライブラリの
シンボル、PIC による静的なライブラリ (libfoo.a) の
シンボルのみに制限されます。その他のコードを使う方法は、
Apache コア自身がすでにそのコードへの参照があるようにするか、
dlopen () を使ってコードを自分自身でロードするかの
どちらかしかありません。Apache HTTP サーバ バージョン 2.0

Apache HTTP サーバは環境変数と呼ばれる、名前のついた 変数に情報を記憶する仕組みを提供しています。この情報はログ収集や アクセス制御などのいろいろな操作を制御するために使うことができます。 これらの変数は CGI スクリプトなどの外部プログラムと通信するためにも 使われます。この文書はそれらの変数の操作方法と使用方法をいくつか 紹介します。
これらの変数は環境変数と呼ばれていますが、オペレーティング システムによって制御されている環境変数と同じではありません。 実際は、これらの変数は Apache の内部構造の中に記憶され、操作されています。 それらは、CGI や SSI スクリプトに渡されたときだけ、実際の オペレーティングシステムの環境変数になります。サーバ自身が 実行されているオペレーティングシステムの環境を操作したい場合は、 オペレーティングシステムのシェルが提供している標準の環境変数の 操作方法を使わなければなりません。
| 関連モジュール | 関連ディレクティブ |
|---|---|
Apache において環境変数を設定する一番基本的な方法は、
無条件に環境変数を設定する SetEnv ディレクティブを使用することです。
PassEnv
ディレクティブにより、Apache が起動されたシェルの
環境変数を渡すこともできます。
より柔軟性を高めるために、mod_setenvif
で提供されているディレクティブを使用することで、リクエストの
特性に基づいて環境変数を設定することができます。例えば、特定のブラウザ
(User-Agent) のリクエストや特定の Referer [意図的な綴りです]
(訳注: 正しい綴りは referrer ですが、HTTP の仕様では Referer
となっています) ヘッダが見つかったときのみ変数を設定することができます。
mod_rewrite の RewriteRule
ディレクティブにおいて環境変数を設定する [E=...]
オプションを使用することで、
より柔軟な設定を行なうことができます。
mod_unique_id は、非常に限られた条件の下で
「すべて」のリクエストについて、一意であることが保証されている値を環境変数
UNIQUE_ID に設定します。
Apache の設定ファイルで設定された環境変数とシェルから渡される 環境変数に加えて、CGI スクリプトと SSI ページには CGI の仕様で要求されている、 リクエストのメタ情報を持った環境変数の組が提供されます。
suexec.c
で定義されます。| 関連モジュール | 関連ディレクティブ |
|---|---|
環境変数の主な利用法の一つは、CGI スクリプトに情報を伝えることです。 上で説明されているように、CGI スクリプトに渡される環境変数は Apache の設定により設定される変数に加えて、リクエストの標準のメタ情報を含んでいます。 詳細は CGI チュートリアル を参照してください。
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=
オプションを使って、環境変数による条件付き適用ができます。
RewriteCond
ディレクティブで評価文字列として
%{ENV:...} 式を指定することで、mod_rewrite
の書き換えエンジンが環境変数に基いて条件分岐を行なうことができます。
mod_rewrite が使用可能な変数で ENV: が前についていない変数は、
実際は環境変数ではないということに注意してください。
それらは他のモジュールからは使用できない mod_rewrite 用の特別な変数です。
互換性の問題を解決するために、特定のクライアントと通信しているときは
Apache の動作を変更できる機構が導入されました。できるだけ柔軟にするために、
これらの機構は環境変数を定義することで呼び出されます。普通は、
BrowserMatch
ディレクティブを使いますが、たとえば SetEnv ディレクティブや PassEnv ディレクティブも使用することができます。
これを指定することで、リクエストが HTTP/1.0 より新しいプロトコルの場合でも、HTTP/1.0 として扱われます。
応答ヘッダがクライアントに送られる前に Vary
フィールドを取り除きます。
クライアントの中にはこのフィールドを正しく解釈しないものがあります
(クライアントの既知の問題
のページを参照してください)。この変数を設定することでその問題を回避
することができます。この変数を設定すると、force-response-1.0
が設定されたことになります。
これが設定されていると、HTTP/1.0 リクエストを発行するクライアントに対しては 常に HTTP/1.0 で応答するようになります。この機能は、 元々は AOL のプロキシの問題のために実装されました。HTTP/1.0 クライアントの中には、 HTTP/1.1 の応答を返されると正しく動作しないものがあるかもしれません。 この機能を使用することで、そのようなクライアントとの間の互換性問題を解決できます。
これが 1 に設定されると、この変数は text/html
以外のコンテントタイプに対する、mod_deflate
提供の DEFLATE 出力フィルタを無効にします。
セットされると、mod_deflate の
DEFLATE フィルタがオフになります。
これが設定されている場合は、KeepAlive を使用しないようにします。
mod_negotiation の挙動に影響を与えます。
(en, ja, x-klingonといった)
言語タグが格納されていれば、その言語の variant を送信しようとします。
そのような variant がない場合は、
通常のネゴシエーション処理が
適用されます。
これはクライアントへのリダイレクトの送信をサーバがより注意深く 行なうようにします。 これは通常、リダイレクトに際してクライアントに 問題があることが分かっている場合に使われます。この機能は元々は マイクロソフトのウェブフォルダのソフトが DAV メソッドによるディレクトリのリソースへのリダイレクトの扱いに 問題がり、それを回避するために実装されました。
Apache 2.0.40 以降で利用可能
クライアントのリクエストに対する応答としてリダイレクトを送信する際、 レスポンスにはリダイレクトが自動的に行なえない (行なわれない) 場合に表示するテキストが含まれます。 通常、このテキストに合致したキャラクタセット、ISO-8859-1 でラベル付けをします。
しかし、リダイレクト先が別の文字セットを使っている場合、 ある問題のあるブラウザのバージョンでは、 リダイレクト先の実際の文字セットの代わりに、 リダイレクト元の文字セットを使ってしまうことがあります。 その結果、例えば変な描画が行なわれたりして、読めなくなったりします。
この環境変数を設定することで、リダイレクションテキストに対する キャラクタセットの指定を除去しますので、それら問題のあるブラウザでも リダイレクト先の文字セットを正しく使うようにできます。
クライアントに関する既知の問題に対処するために、以下の行を 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 」を参照してください。
Apache HTTP Server Version 2.0

The latest version of this FAQ is always available from the main Apache web site, at <http://httpd.apache.org/docs/2.0/faq/>.
Since Apache 2.0 is quite new, we don't yet know what the Frequently Asked Questions will be. While this section fills up, you should also consult the Apache 1.3 FAQ to see if your question is answered there.
If you are having trouble with your Apache server software, you should take the following steps:
/usr/local/apache2/logs/error_log, but see the ErrorLog directive in your config files for the
location on your server.Apache has an active community of users who are willing to share their knowledge. Participating in this community is usually the best and fastest way to get answers to your questions and problems.
USENET newsgroups:
If you've gone through those steps above that are appropriate and have obtained no relief, then please do let the httpd developers know about the problem by logging a bug report.
If your problem involves the server crashing and generating a core dump, please include a backtrace (if possible). As an example,
# cd ServerRoot
# dbx httpd core
(dbx) where
(Substitute the appropriate locations for your ServerRoot
and your httpd and core files. You may have to use
gdb instead of dbx.)
With several million users and fewer than forty volunteer developers, we cannot provide personal support for Apache. For free support, we suggest participating in a user forum.
Professional, commercial support for Apache is available from a number of companies.
Apache uses the sendfile syscall on platforms
where it is available in order to speed sending of responses.
Unfortunately, on some systems, Apache will detect the presence of
sendfile at compile-time, even when it does not work
properly. This happens most frequently when using network or
other non-standard file-system.
Symptoms of this problem include the above message in the error
log and zero-length responses to non-zero-sized files. The
problem generally occurs only for static files, since dynamic
content usually does not make use of sendfile.
To fix this problem, simply use the EnableSendfile directive to disable
sendfile for all or part of your server. Also see
the EnableMMAP, which can
help with similar problems.
If you get error messages related to the AcceptEx syscall
on win32, see the Win32DisableAcceptEx
directive.
Most problems with CGI scripts result in this message written in the
error log together with an Internal Server Error delivered
to the browser. A guide to helping debug this type of problem is
available in the CGI
tutorial.
Apache HTTP Server Version 2.0

Apache uses the sendfile syscall on platforms
where it is available in order to speed sending of responses.
Unfortunately, on some systems, Apache will detect the presence of
sendfile at compile-time, even when it does not work
properly. This happens most frequently when using network or
other non-standard file-system.
Symptoms of this problem include the above message in the error
log and zero-length responses to non-zero-sized files. The
problem generally occurs only for static files, since dynamic
content usually does not make use of sendfile.
To fix this problem, simply use the EnableSendfile directive to disable
sendfile for all or part of your server. Also see
the EnableMMAP, which can
help with similar problems.
If you get error messages related to the AcceptEx syscall
on win32, see the Win32DisableAcceptEx
directive.
Most problems with CGI scripts result in this message written in the
error log together with an Internal Server Error delivered
to the browser. A guide to helping debug this type of problem is
available in the CGI
tutorial.
Apache HTTP Server Version 2.0

The latest version of this FAQ is always available from the main Apache web site, at <http://httpd.apache.org/docs/2.0/faq/>. In addition, you can view this FAQ all in one page for easy searching and printing.
Since Apache 2.0 is quite new, we don't yet know what the Frequently Asked Questions will be. While this section fills up, you should also consult the Apache 1.3 FAQ to see if your question is answered there.
Apache HTTP Server Version 2.0

If you are having trouble with your Apache server software, you should take the following steps:
/usr/local/apache2/logs/error_log, but see the ErrorLog directive in your config files for the
location on your server.Apache has an active community of users who are willing to share their knowledge. Participating in this community is usually the best and fastest way to get answers to your questions and problems.
USENET newsgroups:
If you've gone through those steps above that are appropriate and have obtained no relief, then please do let the httpd developers know about the problem by logging a bug report.
If your problem involves the server crashing and generating a core dump, please include a backtrace (if possible). As an example,
# cd ServerRoot
# dbx httpd core
(dbx) where
(Substitute the appropriate locations for your ServerRoot
and your httpd and core files. You may have to use
gdb instead of dbx.)
With several million users and fewer than forty volunteer developers, we cannot provide personal support for Apache. For free support, we suggest participating in a user forum.
Professional, commercial support for Apache is available from a number of companies.
Apache HTTP サーバ バージョン 2.0

Apache でのフィルタの使い方について記述しています。
| 関連モジュール | 関連ディレクティブ |
|---|---|
フィルタ とは、サーバが送受信したデータに 適用される処理プロセスのことをいいます。クライアントからサーバに 送られたデータは 入力フィルタ によって、サーバから クライアントに送られるデータは出力フィルタによって 処理されます。複数のフィルタを適用することができ、 その順番を厳密に指定することもできます。
Apache 内部では、チャンク (データのぶつ切り) を行ったり、
バイト範囲の指定されたリクエストを扱ったりといった機能を
行う際に、フィルタが使われています。それに加えて、
実行時の設定ディレクティブで選択が可能なフィルタを
モジュールが提供できます。
データに適応されるフィルタのセットは、
SetInputFilter,
SetOutputFilter,
AddInputFilter,
AddOutputFilter,
RemoveInputFilter,
RemoveOutputFilter
ディレクティブで制御できます。
現行の Apache HTTP サーバの配布では、 次のユーザ選択可能なフィルタが提供されています。
mod_include で Server-Side Include をします。mod_deflate
を使って、クライアントに送信する前に出力を圧縮します。また、mod_ext_filter モジュールで
外部プログラムをフィルタとして指定することができます。
Apache HTTP Server Version 2.0

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.
apxs
httpd binary that can be loaded on-demand.INCLUDES output filter
processes documents for → Server Side
Includes.www is a hostname, example.com is a domain name,
and www.example.com is a fully-qualified domain name.
cgi-script handler designates files to be processed as
→ CGIs./usr/local/apache2/conf/httpd.conf, but it may be moved using
run-time or compile-time configuration.GET, POST,
and PUT.
text/html,
image/gif, and application/octet-stream. In
HTTP, the MIME-type is transmitted in the Content-Type
→ header.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./images/.*(jpg|gif)$". Apache uses Perl
Compatible Regular Expressions provided by the PCRE library.
tar utility.
Apache distributions are stored in compressed tar archives or using
pkzip.
http or
https, a hostname, and a path. A URL for this page is
http://httpd.apache.org/docs/2.0/glossary.html.
Apache HTTP サーバ バージョン 2.0

Apache のハンドラの使用に関して記述しています。
| 関連モジュール | 関連ディレクティブ |
|---|---|
「ハンドラ」とは、ファイルが呼ばれたときに実行される動作の Apache における内部表現です。 通常、ファイルはファイル型に基づいた暗黙のハンドラがあります。 普通はすべてのファイルは単にサーバに扱われますが、 ファイルタイプの中には別に「ハンドル」(訳注: 扱う) されるものもあります。
Apache 1.1 では、ハンドラを明示的に使用する機能が追加されました。 ファイルの拡張子や置いている場所に基づいて、 ファイル型と関係なくハンドラを指定することができます。 これはより優雅な解決法という点と、ファイルにタイプとハンドラの両方を関連付けることができるという点で優れています。 (複数の拡張子のあるファイルも参照してください)。
ハンドラはサーバに組み込んだり、モジュールとして含めたり、
Action
ディレクティブとして追加したりすることができます。
以下は標準配布に組み込まれているハンドラです。
default_handelr()
を使ってファイルを送ります。
静的なコンテンツを扱うときにデフォルトで使用されるハンドラです。
(core)mod_asis)mod_cgi)mod_imap)mod_info)mod_status)mod_negotiation)以下のディレクティブによって、拡張子が html
であるファイルは footer.pl
CGI スクリプトを起動するようになります。
Action add-footer /cgi-bin/footer.pl
AddHandler add-footer .html
CGI スクリプトは希望の修正や追加を行なって、元々要求された文書
(環境変数 PATH_TRANSLATED
で指されています) を送る責任があります。
以下のディレクティブは send-as-is
ハンドラを使用するように指示します。このハンドラは自分自身の HTTP
ヘッダを持っているファイルに使用されます。ここでは、拡張子に関わらず、
/web/htdocs/asis ディレクトリにある全てのファイルは
send-as-is ハンドラによって扱われます。
<Directory /web/htdocs/asis>
SetHandler send-as-is
</Directory>
ハンドラの機能を実装するために、利用すると便利かもしれないものが
Apache API
に追加されました。詳しく言うと、request_rec
構造体に新しいレコードが追加されたということです。
char *handler
もしモジュールがハンドラに関わりたい場合、
やらなければならないことは、リクエストが invoke_handler
ステージに達する以前に r->handler
を設定することだけです。ハンドラはコンテントタイプの代わりに
ハンドラ名を使うようになっていること以外は、以前と同じように実装されています。
必ず要求されているわけではありませんが、メディアタイプ
の名前空間を侵さないように、ハンドラの名前にはスラッシュを含まない、
ダッシュ (訳注: "-") で分離された名前を付ける習慣になっています。
Apache HTTP サーバ バージョン 2.0

「認証」とは、誰かが自分は誰であるかを主張した場合に、 それを確認するための全過程を指します。「承認」とは、 誰かが行きたい場所に行けるように、あるいは欲しい情報を 得ることができるようにするための全過程を指します。
| 関連モジュール | 関連ディレクティブ |
|---|---|
もし機密の情報や、ごくごく少数グループの人向けの情報を ウェブサイトに置くのであれば、この文書に書かれている テクニックを使うことで、そのページを見ている人たちが 望みの人たちであることを確実にできるでしょう。
この文書では、多くの人が採用するであろう、 ウェブサイトの一部分を保護する「一般的な」 方法についてカバーしています。
この文書で取り扱われるディレクティブは、
メインサーバ設定ファイル (普通は
<Directory>
セクション中) か、あるいはディレクトリ毎の設定ファイル
(.htaccess ファイル) かで用います。
.htaccess ファイルを用いるのであれば、
これらのファイルに認証用のディレクティブを置けるように
サーバの設定をしないといけないでしょう。これは
AllowOverride
ディレクティブで可能になります。
AllowOverride
ディレクティブでは、ディレクトリ毎の設定ファイル中に置くことのできる
ディレクティブを、もしあれば、指定します。
認証について話を進めているので、次のような
AllowOverride
ディレクティブが必要になるでしょう。
AllowOverride AuthConfig
そうでなく、メインサーバ設定ファイルの中に 直接置くのであれば、当然ながらそのファイルへの書き込み 権限を持っていなければならないでしょう。
また、どのファイルがどこに保存されているか知るために、 サーバのディレクトリ構造について少し知っておく 必要があるでしょう。 これはそんなに難しくないので、この文書中で ディレクトリ構造について知っておく必要がある場面では、 明らかになるようにします。
では、サーバ上のあるディレクトリをパスワードで保護する 基本手順を示します。
パスワードファイルを作る必要があります。
このファイルは、ウェブからアクセスできる場所に
置くべきではありません。他の人がパスワードファイルを
ダウンロードできないようにするためです。例えば、
/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 認証はクライアントからブラウザへ、
パスワードを暗号化せずに送ります。ですから、
この方法は特に機密性の高いデータに対しては用いるべきでは
ありません。 Apache ではもう一つ別の認証方法:
AuthType Digest をサポートしています。
この方法は mod_auth_digest
で実装されていて、もっと安全です。
ごくごく最近のクライアントしか Digest
認証をサポートしていないようです。
AuthName
ディレクティブでは、認証に使う Realm (訳注: 領域)
を設定します。Realm は大きく分けて二つの機能を提供します。
一つ目は、クライアントがパスワードダイアログボックスの
一部としてユーザにこの情報をよく提示する、というものです。
二つ目には、クライアントが与えられた認証領域に対してどのパスワードを
送信すれば良いのかを決定するために使われる、という機能です。
例えば、"Restricted Files" 領域中で
一度認証されれば、同一サーバ上で "Restricted Files"
Realm としてマークされたどんな領域でも、クライアントは
自動的に同じパスワードを使おうと試みます。
このおかげで、複数の制限領域に同じ realm を共有させて、
ユーザがパスワードを何度も要求される事態を
防ぐことができます。もちろん、セキュリティ上の理由から、
サーバのホスト名が変わればいつでも必ず、
クライアントは再びパスワードを尋ねる必要があります。
AuthUserFile
ディレクティブは htpasswd で作った
パスワードファイルへのパスを設定します。
ユーザ数が多い場合は、リクエスト毎のユーザの認証のための
プレーンテキストの探索が非常に遅くなることがあります。
Apache ではユーザ情報を高速なデータベースファイルに
保管することもできます。
mod_auth_dbm モジュールが
AuthDBMUserFile
ディレクティブを提供します。これらのファイルは dbmmanage
プログラムで作成したり操作したりできます。
Apache
モジュールデータベース中にあるサードパーティー製の
モジュールで、その他多くのタイプの認証オプションが
利用可能です。
最後に、Require
ディレクティブが、サーバのこの領域にアクセスできるユーザを
指定することによって、プロセスの承認部分を提供します。
次のセクションでは、Require
ディレクティブの様々な用法について述べます。
上記のディレクティブは、ただ一人 (具体的にはユーザ名
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
ディレクティブに正しいファイルを参照させなければならない点です。
Basic 認証が指定されている場合は、 サーバにドキュメントをリクエストする度に ユーザ名とパスワードを検査しなければなりません。 これは同じページ、ページにある全ての画像を リロードする場合であっても該当します (もし画像も保護されたディレクトリから来るのであれば) 。 予想される通り、これは動作を多少遅くします。 遅くなる程度はパスワードファイルの大きさと比例しますが、 これは、ファイルを開いてあなたの名前を発見するまで ユーザ名のリストを読まなければならないからです。 そして、ページがロードされる度にこれを行わなければ なりません。
結論としては、一つのパスワードファイルに置くことのできる ユーザ数には実質的な限界があります。 この限界はサーバマシンの性能に依存して変わりますが、 数百のエントリを越えたあたりから速度低下が見られると予期されています。 その時は他の認証方法を考慮に入れた方が良いでしょう。
ユーザ名とパスワードによる認証は認証の一つの方法に過ぎません。 しばしば誰であるかということとは違う何かに基づいて、 入れるようにしたくなることもあるでしょう。 例えばその人がどこから来ているかといったことです。
Allow と
Deny
ディレクティブを使って、ドキュメントを要求してきたマシンの
ホスト名やホストアドレスに基づいて許可不許可を制御できます。
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 を使うことで、
Deny と
Allow の組み合わせで
入っても良いグループが本当に確実に限定できているようにできます。
Order deny,allow
Deny from all
Allow from dev.example.com
Allow
ディレクティブを単純に列挙するのでは望みの動作をしないでしょう。
なぜなら、全ての人が入れるということに加えて、
指定したホストからの人が入れるようにするからです。
やりたいことは、指定した人たちだけが入れるように
することです。
これら全てがどのように動作するかについて
もっと多くの情報が書かれている mod_auth と
mod_access
の文書も読むとよいでしょう。
Apache HTTP サーバ バージョン 2.0

| 関連モジュール | 関連ディレクティブ |
|---|---|
CGI (Common Gateway Interface) は、ウェブサーバが コンテンツ生成をする外部プログラムと協調して動作するための方法を 定義しています。そのプログラムはしばしば CGI プログラムや CGI スクリプトと呼ばれます。CGI は、ウェブサイトに動的な コンテンツを置くための最も簡単で一般的な方法です。このドキュメントは、 Apache ウェブサーバで CGI を設定し、 CGI プログラムを書き始めるための入門書となるでしょう。
CGI プログラムを正しく動作させるには、CGI を許可するように Apache の設定を行う必要があります。 これを行なうための方法がいくつかあります。
ScriptAlias
ディレクティブを使用して、
CGI プログラム用の特別な別ディレクトリを Apache に設定します。
Apache は、このディレクトリ中の全てのファイルを CGI
プログラムであると仮定します。
そして、この特別なリソースがクライアントから要求されると、
そのプログラムの実行を試みます。
ScriptAlias
ディレクティブは以下のように使用します:
ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/
デフォルト位置に Apache をインストールしたならば、
この例はデフォルト状態の httpd.conf
設定ファイルに含まれています。
ScriptAlias
ディレクティブは、URL の前に付加するディレクトリを定義する
Alias
ディレクティブとかなり似ています。
Alias と ScriptAlias
は通常、DocumentRoot
ディレクトリ外のディレクトリのために使用されます。
Alias と ScriptAlias
との差は、ScriptAlias が接頭辞で始まるすべての
URL は CGI プログラムとみなされるという追加の意味を含んでいることです。
従って、上記の例では、/cgi-bin/
で始まるリソースへのあらゆるリクエストに対して、ディレクトリ
/usr/local/apache2/cgi-bin/ から提供し、それらを
CGI プログラムとして扱うよう Apache に示します。
例えば、URL http://dev.rcbowen.com/cgi-bin/test.pl
が要求された場合、Apache は ファイル
/usr/local/apache2/cgi-bin/test.pl
を実行し、その出力を返すことを試みます。
もちろん、ファイルが存在し、実行可能であり、決められた方法で出力を返します。
そうでなければ、Apache はエラーメッセージを返します。
CGI プログラムは、セキュリティ上の理由から
ScriptAlias
されたディレクトリに制限されることがしばしばあります。この方法により、
CGI プログラムを使用できるユーザを管理者が厳しく制御することができます。
しかしながら、適切なセキュリティ事前対策がとられるならば、CGI
プログラムを任意のディレクトリで実行できないようにする理由はありません。
例えば、ユーザに UserDir
ディレクティブで彼らのホームディレクトリ配下にウェブコンテンツを持たせたいとします。
もし、彼らが CGI プログラムを持つことを望んでいても、メインの
cgi-bin ディレクトリへのアクセスができない場合、
CGI プログラムを実行することができる他の場所が必要になります。
任意のディレクトリで CGI の実行を許可するには二段階の設定が必要です。
まず、AddHandler や SetHandler ディレクティブによって
cgi-script ハンドラが可能になっている必要があります。
次に、Options ディレクティブで
ExecCGI が指定されていなければなりません。
サーバのメインの設定ファイル中で Options
ディレクティブを明示的に使用することで、特定のディレクトリ配下で
CGI の実行を許可するように指定することができます:
<Directory /usr/local/apache2/htdocs/somedir>
Options +ExecCGI
</Directory>
上記ディレクティブは、CGI ファイルの実行を可能にするよう
Apache に伝えます。また、どのファイルが CGI ファイルかを
サーバに伝える必要があります。次の
AddHandler
ディレクティブの例では、cgi または pl
を拡張子に持つすべてのファイルを CGI
プログラムとしてみなすことをサーバに伝えます:
AddHandler cgi-script .cgi .pl
.htaccess チュートリアル
は httpd.conf を変更できない場合にどうやって CGI プログラムを
使えるようにするかを説明しています。
.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>
「通常の」プログラミングと CGI プログラミングの間には主に二つの違いがあります。
一つは、CGI プログラムのすべての出力には MIME-type ヘッダを付けなければなりません。 これはどのような種類のコンテンツを受け取っているかをクライアントに示す HTTP ヘッダです。ほとんどの場合では、次のように出力します:
Content-type: text/html
もう一つは、出力を HTML か、ブラウザが表示することができる何か他の形式にする必要があります。 大抵の場合は HTML でしょうが、GIF イメージや他の非 HTML コンテンツを出力する 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 行がブラウザウィンドに現れるでしょう。
それはあまりエキサイティングなことではありません。
しかし、これがうまく動けば、
他のどのようなものでも動かすことができるようになります。
ウェブから CGI プログラムへのアクセスを行なったとき、 ブラウザで見る可能性がある四つの基本的なことがあります:
Content-Type を CGI プログラム内で
セットしたかを確認してください。サーバはあなたの権限で実行されていないのを忘れないように。
つまり、起動するとき、サーバは特権をもたないユーザ - 通常 nobody
や www の権限で実行されます。したがって、あなたが所有する
ファイルを実行するには別のパーミッションが必要となります。
通常、nobody が実行するのに十分なパーミッションを与える方法は、
ファイルに誰でも実行可能とするパーミッションを与えることです:
chmod a+x first.pl
また、もしあなたのプログラムが他のファイルを読み書きするならば、 それらのファイルは、これが可能となる正しいパーミッション を持っている必要があります。
コマンドラインからプログラムを実行するとき、
意識しなくてもシェルに渡される情報があります。
例えば、参照するファイルのためにどこを検索したらよいかを
シェルに伝える PATH があります。
プログラムが CGI プログラムとしてウェブサーバによって実行されるとき、
それは同じ PATH ではないかもしれません。
CGI プログラム内で呼び出すあらゆるプログラム
(例えば、sendmail のようなもの) は、
フルパスで指定する必要があるでしょう。それにより、CGI
プログラムを実行しようとしたとき、
シェルはそのようなプログラムを見つけることができます。
同様なことは、スクリプトのインタプリタ (しばしば perl)
へのパスで、CGI プログラムの 1 行目に次のように示されます:
#!/usr/bin/perl
これがインタープリタへの実際のパスであることを確実にしておきます。
CGI プログラムが失敗するのは大抵、プログラム自身に問題がある場合です。 一度 CGI の使い方を理解し、前述の二つの誤りを犯していないならば、 まず間違いなくそうでしょう。ブラウザを使ってテストする前に まず確認することは、コマンドラインからプログラムが実行できることです。 例えば、以下を実行してみてください:
cd /usr/local/apache2/cgi-bin
./first.pl
(perl インタプリタは呼ばないでください。
シェルと Apache がスクリプトの最初の行の パス情報 を使って見つけます。)
最初にプログラムから出力されるのは Content-Type を含み、
後に空行の続く HTTP ヘッダでなければなりません。他のものが出力されている
場合は、Apache はこのプログラムをサーバ経由で実行しようとしたときには
Premature end of script headers エラーを出力します。詳細は
上記の CGI プログラムを書く を読んでください。
エラーログは友達です。 全てのうまくいかないことは、エラーログにメッセージを生成します。 必ずそれを最初に見るべきです。 もし、あなたがウェブサイトを主催している場所が エラーログの参照を許していないならば、きっと他のサイトで主催するべきです。 エラーログの読み方を学ぶことで、ほとんど全ての問題が迅速に確認され、 迅速に解決されるということが分かるでしょう。
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 の
ログファイルの位置を調べ、そのログファイルを使ってポリシー違反を
見つけてください。
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 は通常コンソールまたはスクリーンを意味します。
ウェブフォームから CGI プログラムへPOST
したとき、フォームのデータは特別なフォーマットで束ねられ、
STDIN を通して、CGI プログラムに引き渡されます。
プログラムはデータがキーボード
もしくはファイルから来ていたかのように処理することができます。
「特別なフォーマット」はとても単純です。フィールド名と値はイコール (=) で結ばれます。そして値の組はアンパサンド (&) で結ばれます。 スペース、アンパサンド、イコールのような面倒な文字は、 それらが動作を駄目にしないようにその文字に相当する 16 進に変換されます。 全データ文字列は、以下のようになります:
name=Rich%20Bowen&city=Lexington&state=KY&sidekick=Squirrel%20Monkey
時々、このような文字列が URL
に付加されるのを見るでしょう。その場合、サーバは
QUERY_STRING という環境変数にその文字列を入れます。それは
GET リクエストと呼ばれます。
HTML フォームでは、データを渡すために GET と
POST のどちらを使用するかを、FORM タグの
METHOD 属性の設定で指定します。
CGI プログラムは、その文字列を役に立つ情報に分割する責任があります。 幸いにも、そのデータ処理を助けるライブラリやモジュールが存在します。 これらは、CGI プログラムの他の面でも同様に役に立ちます。
CGI プログラムを書くとき、面倒な仕事の大部分をしてくれる コードライブラリまたはモジュールを使うことを検討すべきです。 これはエラーを減らし、早い開発につながります。
Perl で CGI プログラムを書いているなら、モジュールは CPAN で提供されています。
この目的のための最も普及しているモジュールは CGI.pm です。
CGI::Lite も検討しましょう。これは、ほとんどのプログラム
において必要とするすべての機能の最小セットの実装です。
C で CGI プログラムを書いているなら、いろいろな
オプションがあります。これらの内の一つは http://www.boutell.com/cgic/
で提供されている CGIC ライブラリです。
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 バグデータベースに送るべきでない ことに注目してください。
Apache HTTP サーバ バージョン 2.0

.htaccess ファイルはディレクトリ毎に設定を変更する方法を
提供します。
| 関連モジュール | 関連ディレクティブ |
|---|---|
.htaccess ファイル (「分散設定ファイル」) は
ディレクトリ毎に設定を変更する方法を提供します。ディレクティブの
書かれたファイルをディレクトリに置くことで、そのディレクトリとその
サブディレクトリすべてにディレクティブを適用させることができます。
.htaccess ファイルを別の名前にしたい場合は、
AccessFileName ディレクティブを
使って変更することができます。例えば、そのファイルを .config
という名前にしたい場合は、以下の設定をサーバ設定ファイルに入れることが
できます:
AccessFileName .config
一般に、.htaccess ファイルの構文は
主設定ファイル
と同じです。これらのファイルに書くことのできるディレクティブは AllowOverride ディレクティブにより決まります。
このディレクティブは、.htaccess ファイルに
書かれたディレクティブの中で、、
どのディレクティブが適用されるかをカテゴリー単位で指定します。
.htaccess に書くことのできるディレクティブであれば、
説明文書には「上書き」という項目があり、.htaccess に書くことができるように
なるための AllowOverride の値が指定されています。
例えば、AddDefaultCharset ディレクティブの説明を
見ると、.htaccess ファイルでの使用が許可されていることが
わかります。 (ディレクティブの概要の所にある「コンテキスト」と書かれている
行を見てください。) 上書きと書かれている行には
FileInfo とあります。ですから、.htaccess 中の
このディレクティブが有効になるためには、少なくとも
AllowOverride FileInfo が設定されている必要があります。
あるディレクティブを .htaccess ファイルに書くことができるか
どうかわからないときは、そのディレクティブの説明を探して、".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
.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 ファイルを使う必要がある、というものがあります。
これは正しくありません。主サーバ設定ファイルの <Directory> セクションに
認証用のディレクティブを書く方が推奨される方法で、.htaccess
ファイルは主サーバ設定ファイルを変更できないときにのみ使用すべきです。
いつ .htaccess ファイルを使うべきで、いつ使うべきではないかに
ついては 上を参照してください。
以上のことをふまえた上で、もし .htaccess の使用が
まだ必要だと思う場合は、次のようなものが望みのことをしてくれるかも
しれません。
ディレクティブが適用されるためには、
"AllowOverride AuthConfig" の設定がなされている
必要があります。
.htaccess ファイルの内容:
AuthType Basic
AuthName "Password Required"
AuthUserFile /www/passwords/password.file
AuthGroupFile /www/passwords/group.file
Require Group admins
これらのディレクティブが有効になるためには、
AllowOverride AuthConfig が有効でなくてはならないことに
注意してください。
認証と承認については 認証チュートリアルを 参照してください。
もう一つの .htaccess ファイルのよくある利用法は
特定のディレクトリで SSI を有効にすることです。これは、望みのディレクトリの
.htaccess ファイルに以下の設定ディレクティブを書くことで
達成できます:
Options +Includes
AddType text/html shtml
AddHandler server-parsed shtml
これらのディレクティブが有効になるためには、
AllowOverride Options と AllowOverride
FileInfo が有効になっている必要があることに注意してください。
よりまとまった SSI の説明は SSI チュートリアルを 参照してください。
最後に、特定のディレクトリで CGI プログラムの実行を許可したいことが あるでしょう。これは以下の設定で行なうことができます:
Options +ExecCGI
AddHandler cgi-script cgi pl
もしくは、あるディレクトリのすべてのファイルが CGI プログラムと みなされるようにしたいなら、以下の設定で実現することができます:
Options +ExecCGI
SetHandler cgi-script
これらのディレクティブが有効になるためには、
AllowOverride Options と AllowOverride
FileInfo が有効である必要があることに注意してください。
CGI プログラムと設定のよりまとまった説明は CGI チュートリアルを参照してください。
設定ディレクティブを .htaccess ファイルに書いたけれども、
期待した効果が得られないときには、いくつかの原因が考えられます。
一番よくあることは、設定ディレクティブが考慮されるようには
AllowOverride が設定されていない
というものです。該当のファイルのスコープに AllowOverride None
が設定されていないことを確認してください。これを調べるための良い方法は、
.htaccess ファイルにごみを書いて、リロードすることです。
サーバのエラーが生成されないときは、ほぼ確実に AllowOverride
None が設定されている状態になっています。
そうではなく、文書をアクセスしようとしたときにエラーが発生している
ときは、Apache のエラーログを調べてください。.htaccess ファイルで
使用されたディレクティブが許可されていない、ということを知らせている
可能性が高いです。または、構文の間違いがあることを述べているかもしれません。
その場合にはまずそれを修正する必要があります。
Apache HTTP サーバ バージョン 2.0

認証とは、誰かが自分は誰であるかを名乗っているものを検証する 処理のことです。承認とは、誰かが望みの場所に辿り着けたり、 望みの情報を手に入れたりすることを許可する処理のことです。
参照: 認証、承認、アクセス制御
CGI (Common Gateway Interface) はウェブサーバが外部のコンテンツ 生成プログラムとどのように相互動作をするかを定義します。 その外部プログラムは通常 CGI プログラムや CGI スクリプトと呼ばれます。 CGI はウェブサイトに動的なコンテンツを追加するための、 一番単純でよく使われている方法です。この文書は Apache ウェブサーバに CGI を設定し、CGI プログラムを書き始めるためのイントロダクションです。
参照: CGI: 動的コンテンツ
.htaccess ファイル.htaccess ファイルはディレクトリ毎に設定を変更するための
方法を提供します。設定ディレクティブが書かれたファイルが、あるドキュメント
ディレクトリに置かれると、ディレクティブはそのディレクトリと
すべてのサブディレクトリに適用されます。
参照: .htaccess ファイル
SSI (Server Side Includes) は HTML ページ中に書かれるディレクティブで、 ページが送られる時にサーバにより評価されます。これにより、ページ全体を CGI プログラムで生成したり、他の動的な技術を使うことなく、既存の HTML ページに動的に生成された内容を付加することができます。
Apache HTTP サーバ バージョン 2.0

複数のユーザのいるシステムでは、UserDir ディレクティブを使って
各ユーザがホームディレクトリにウェブサイトを構築できるように設定することが
可能です。URL http://example.com/~username/ を訪れた人は
"username" というユーザの 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 へ変換されます。
UserDir のドキュメントに示されている構文を使うことで、 どのユーザがこの機能を使うことができるかを制限することができます:
UserDir enabled
UserDir disabled root jro fish
上の設定は dissabled 文のユーザ以外のすべてのユーザに
対して UserDir の機能を有効にします。同様にして、以下のように
数名のユーザ以外に対してこの機能を無効にすることもできます:
UserDir disabled
UserDir enabled rbowen krietz
他の例は UserDir
の説明を参照してください。
それぞれのユーザに専用の cgi-bin ディレクトリを与えるために、
<Directory>
を使ってユーザのホームディレクトリの指定された領域に対して CGI を有効に
することができます。
<Directory /home/*/public_html/cgi-bin/>
Options ExecCGI
SetHandler cgi-script
</Directory>
そして、UserDir が
public_html に設定されていると仮定すると、
そのディレクトリの CGI プログラム example.cgi
は以下の様に呼び出されることができます:
http://example.com/~rbowen/cgi-bin/example.cgi
ユーザに彼らのウェブ空間でのサーバの設定の変更を許可する場合、
ユーザは .htaccess ファイルを使って設定を変更する必要があります。
AllowOverride の値を
ユーザが変更することを許可したいディレクティブに対して十分なものに
設定していることを確認してください。この機能がどのようにして動作しているか
の詳細は .htaccess チュートリアル を読んで
ください。
Apache HTTP サーバ バージョン 2.0

サーバサイドインクルードによって、既存の HTML ドキュメントに動的なコンテンツを追加することができます。
| 関連モジュール | 関連ディレクティブ |
|---|---|
この記事は、通常は単に SSI と呼ばれる Server Side Includes を扱います。この記事においては、サーバでの SSI を許可するための設定と、 現在の HTML ページに動的なコンテンツを加えるためのいくつかの基本的な SSI 技術を紹介します。
記事の後半では、SSI ディレクティブで SSI と共に実行することができる条件文のような 幾分高度な事柄について述べています。
SSI (Server Side Includes) は、HTML ページ中に配置されるディレクティブであり、 サーバでページを提供する時に評価されます。SSI は、CGI プログラムやその他の動的な技術で全てのページを提供せずに、 動的に生成されたコンテンツを現在の HTML ページに加えます。
どういう場合に SSI を使い、どういう場合にプログラムで ページを完全に生成するかは、ページのうちどの程度が静的であり、 ページが提供されるたびに再計算する必要がどの程度あるかで通常は決定します。 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 ヘッダに送りません。 動的なコンテンツであるため、それらの値を計算するのが難しいからです。 このためドキュメントがキャッシュされなくなり、 結果としてクライアントの性能が遅くなったように感じさせることになります。 これを解決する方法が二つあります:
XBitHack Full 設定を使用する。
この設定により、もともと要求されたファイルの時刻を参照し、
読み込まれるファイルの変更時刻を無視して最終変更時刻を決定するよう
Apache に伝えます。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 プログラムの結果を出力する SSI のより一般的な使用のうちの一つです。
<!--#include virtual="/cgi-bin/counter.pl" -->
以下は、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 ディレクティブは、挿入用のファイルに含ませたり、
挿入ファイルのネストをしたりすることができます。すなわち、
挿入用のファイルは他のファイルを再帰的に挿入することができます。
時刻書式を 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 を指定することができます。
今後数ヶ月のうちに、小さな 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
機能は許可しないようにすることができます。
コンテンツを出力することに加え、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
に頼ることなくかなり複雑な動的なことをさせることができます。
SSI は確かに CGI や動的なウェブページを生成する他の技術に代わるものではありません。 しかし、たくさんの余分な作業をせずに、 少量の動的なコンテンツを加えるにはすぐれた方法です。