symfonyで複数アプリケーションの運用


symfonyでプロジェクトに複数アプリケーションを作成して、それぞれにサブドメインを設定して運用を行う場合のメモ。



symfonyではwebディレクトリ内にアプリケーション毎に「(appname).php」ができるので、hogeとfugaいうアプリケーションを作った場合URLはそれぞれ

 http://example.com/hoge.php
 http://example.com/fuga.php

になる。これで運用すると気持ち悪いので「.htaccess」に以下のようなルールを書く。

web/.htaccess

  RewriteEngine On

  RewriteCond %{REQUEST_URI} \..+$
  RewriteCond %{REQUEST_URI} !\.html$
  RewriteRule .* - [L]

  RewriteRule ^$ index.html [QSA]
  RewriteRule ^([^.]+)$ $1.html [QSA]
  RewriteCond %{REQUEST_FILENAME} !-f
  
  RewriteCond %{HTTP_HOST} ^hoge\.
  RewriteRule ^(.*)$ hoge.php [QSA,L]
  
  RewriteCond %{HTTP_HOST} ^fuga\.
  RewriteRule ^(.*)$ fuga.php [QSA,L]

こうすることで、

 「http://hoge.example.com」へのアクセスは「hoge.php」へ
 「http://fuga.example.com」へのアクセスは「fuga.php」へ流れる。と思う。


もちろんApacheのバーチャルホスト設定で両ドメインとも使えるように以下のような感じで設定する。

httpd.conf

<VirtualHost *>
    ServerName hoge.example.com
    ServerAlias fuga.example.com
    DocumentRoot "[$symfony_project_root]/web"
    Alias /sf [$symfony_data_dir]/web/sf
    <Directory "[$symfony_data_dir]/web/sf">
        AllowOverride All
        Allow from All
    </Directory>
    <Directory "[$symfony_project_root]/web">
        AllowOverride All
        Allow from All
    </Directory>
</VirtualHost>


これでとりあえずは各ドメインでうまくアクセスできるようになるのだが、デフォルトではドメイン間のセッション情報が引き継がれないのでちょっと困る。

なので、セキュリティ的にどうこうは置いといて、セッションをサブドメイン間で共有できるように以下の設定を行う。

app/config/factories.yml

all:
  storage:
    class:                    sfMySQLSessionStorage
    param:
      db_table:               session
      db_id_col:              id
      db_data_col:            data
      db_time_col:            updated_at
      database:               propel
      session_cookie_domain:  .example.com

StorageにMysqlを使う場合は上のような感じで。パラメータ「session_cookie_domain」をサブドメイン間で共有できるように設定する。


これで複数アプリケーションの運用ができるようになる。