LoginSignup
3
4

More than 5 years have passed since last update.

VirtualDocumentRootを使ってサブドメインを活用する

Last updated at Posted at 2015-06-11

事の発端

CakePHPの環境を作るたびにApacheのVirtualHost設定するのが面倒なので、サブドメインでアクセスできるようにApacheの設定を行おう!

*.hoge.example.comでバーチャルホストを切れるように設定する

環境

  • Apache2.2
    • VirtualDocumentRootを使うのでmod_vhost_aliasが必須

DNSレコード設定

Aレコードに*.hoge.example.comがWebサーバに向くように設定する。

Apacheの設定

Apacheの設定ファイルにVirtualHostの設定を追加する。
<VirtualHost *:80>
    ServerName hoge.example.com
    ServerAlias *.hoge.example.com
    VirtualDocumentRoot /var/www/hoge.example.com/%1
    CustomLog    logs/hoge.example.com_access_log combined
    ErrorLog     logs/hoge.example.com_error_log
    # 必要に応じて追加
    <Directory "/var/www/hoge.example.com/%1">
        AllowOverride All
        Options FollowSymlinks
    </Directory>
</VirtualHost>
Apacheを再起動して設定を反映させる。
% sudo apachectl configtest
Syntax OK
% sudo apachectl restart

これで以下の通りにマッピングされる。

ホスト名 ディレクトリ
fuga.hoge.example.com /var/www/hoge.example.com/fuga
piyo.hoge.example.com /var/www/hoge.example.com/piyo

その他捕捉

CakePHP3を実行しようとしたところそのままだとリダイレクトループに陥ってしまうので、.htaccessにRewriteBaseを追記する。

CAKE/.htaccess
 <IfModule mod_rewrite.c>
     RewriteEngine on
+    RewriteBase /
     RewriteRule    ^$    webroot/    [L]
     RewriteRule    (.*) webroot/$1    [L]
 </IfModule>
CAKE/webroot/.htaccess
 <IfModule mod_rewrite.c>
     RewriteEngine On
+    RewriteBase /
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteRule ^ index.php [L]
 </IfModule>
3
4
0

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
3
4