LoginSignup
9
10

More than 5 years have passed since last update.

ApacheのVirtualDocumentRootでハマった

Posted at

最近Chefが好きなaraiです。

Chefとは関係ないですが、ApacheのバーチャルホストでVirtualDocumentRootを使用して、ちょっとハマったのでメモです。

通常ドキュメントルートはこんな感じ。
DocumentRoot /var/www/vhosts/example.jp/httpdocs
バーチャルドキュメントルートは以下のように記述。
VirtualDocumentRoot /var/www/vhosts/%0/httpdocs

これで設定したら、色々とハマった。

問題①

PHPで以下のように、別ファイルをインクルードすると、ApacheのデフォルトDocumentRoot(/var/www/html)を見てしまい、エラーになる。

index.php
                      :
  <?php include($_SERVER['DOCUMENT_ROOT'] . '/common/header.php'); ?>
                      :

エラー内容

include(/var/www/html/common/header.php): failed to open stream: No such file or directory in /var/www/vhosts/example.jp/httpdocs/index.php

原因

PHPでサーバ環境変数 $_SERVER['DOCUMENT_ROOT'] がApacheのデフォルトDocumentRootを見てしまい、エラーになる。

解決方法

以下ファイルを作成し、Apache側でphp_admin_value auto_prepend_fileで読み込む。

/etc/httpd/conf/vhosts/example_document_root.php
<?php
$_SERVER['DOCUMENT_ROOT'] = "/var/www/vhosts/example.jp/httpdocs";
?>
/etc/httpd/conf/vhosts/example.jp.conf
<VirtualHost *:80>
    VirtualDocumentRoot /var/www/vhosts/%0/httpdocs
    php_admin_value auto_prepend_file /etc/httpd/conf/vhosts/example_document_root.php
          :
          :
</VirtualHost>

※ 上記ファイルはhttpd.confよりIncludeしてます。

問題②

httpではなく、CLIからPHPを実行すると、PHP内に記述している、$_SERVER['DOCUMENT_ROOT']がApacheのデフォルトドキュメントルート(/var/www/html)を見てしまう。

原因

①同様、PHPでサーバ環境変数 $_SERVER['DOCUMENT_ROOT'] がApacheのデフォルトDocumentRootを見てしまい、エラーになる。

解決方法

PHPで以下のようにサーバ環境変数を書き換える。
$_SERVER['DOCUMENT_ROOT'] = "/var/www/vhosts/example.jp/httpdocs";

問題③

リライト先のドキュメントルートが変わる。
問題①、問題②を解決した状態で、以下のようなリライトを設定すると、問題①同様ドキュメントルートがApacheのデフォルトドキュメントルート(/var/www/html)になってしまう。

/etc/httpd/conf/vhosts/example.jp.conf
RewriteEngine on
RewriteRule ^(/|/index.php)$ /hoge/test.php

原因

ディレクトリディレクティブ外に記述すると、リライト先がApacheのデフォルトドキュメントルート(/var/www/html)を見てしまう。

解決方法

RewriteはDirectoryディレクティブの中に入れることで解決した。

最終的なVirtualHost設定内容

/etc/httpd/conf/vhosts/example.jp.conf
<VirtualHost *:80>
    VirtualDocumentRoot /var/www/vhosts/%0/httpdocs
    php_admin_value auto_prepend_file /etc/httpd/conf/vhosts/example_document_root.php   #←サーバ変数書き換え
    ServerName   example.jp
    ServerAlias  www.example.jp
    ErrorLog /var/log/httpd/example.jp_error_log
    LogLevel warn
        LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %v" combined
    CustomLog /var/log/httpd/example.jp_access_log "combined"
    <Directory /var/www/vhosts/example.jp/httpdocs/>
        AllowOverride All
        DirectoryIndex index.php index.html index.htm

        RewriteEngine on    #←RewriteはDirectoryディレクティブの中で記述する
        RewriteRule ^(/|/index.php)$ /hoge/test.php
    </Directory>
</VirtualHost>
9
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10