LoginSignup
7
8

More than 5 years have passed since last update.

CakePHP2.7.8セットアップ手順(さくらVPS/CentOS6.6/PHP5.3.3/Postgresql8.4)

Last updated at Posted at 2015-07-18

自分でおさらいしたところ、抜け・漏れがあったので修正しました(2015/07/19 15:10)
2.6.7に加え、2.7.8でも動作確認できました(2016/01/01 08:50)


0. はじめに

本手順書では、sshd_configの設定からDebugKitの導入までをカバーしています。
CentOS6.6の標準のrpmを使います。

1. セキュリティ対策

1.1 sshdの設定変更

セキュリティ上の懸念事項を潰すことから始めます。
さくらVPSのsshdの設定はデフォルトでパスワード認証なので、これを公開鍵認証に変更します:

cd /root
mkdir .ssh
chmod 700 .ssh
touch .ssh/authorized_keys
chmod 600 .ssh/authorized_keys
vi /root/.ssh/authorized_keys
(公開鍵を追加)
vi /etc/ssh/sshd_config

【注意】
sshd_configと似た名前のssh_configなるファイルがありますが、
そちらを編集してもsshdの設定変更できないのでご注意ください。

私はrootログイン許可、パスワードログイン拒否、公開鍵認証必須なのでssh_configを次のように設定しました:

sshd_config
Protocol 2

SyslogFacility AUTHPRIV

PermitRootLogin                 yes
RSAAuthentication               no
PubkeyAuthentication            yes
AuthorizedKeysFile              .ssh/authorized_keys

PermitEmptyPasswords            no
PasswordAuthentication          no

ChallengeResponseAuthentication no

GSSAPIAuthentication            no
GSSAPICleanupCredentials        no

UsePAM                          yes

AcceptEnv                       LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv                       LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv                       LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv                       XMODIFIERS

X11Forwarding                   no
Subsystem                       sftp    /usr/libexec/openssh/sftp-server

sshdを再起動します。再起動後、ターミナルを閉じないように!

service sshd restart

1.2 sshdの設定変更をテスト

ターミナルをもう1つ開き、次のテストを行います:

  • パスワードでログインできないこと
  • 秘密鍵でログインできること

1.3 ipv6をOFFにする

利用しないものはOFFにするポリシーなのでipv6をOFFにします。
その際、ついでにホスト名も設定します。

vi /etc/sysconfig/network
/etc/sysconfig/network
NETWORKING=yes
HOSTNAME=(ホスト名)
NETWORKING_IPV6="no"
IPV6_DEFAULTDEV="eth0"
IPV6_DEFAULTGW="fe80::1"

1.4 rpmを最新にする

更新すべきrpmの有無を確認します:

yum clean all
yum check-update

アップデートすべきrpmがあったら、

yum update

でアップデートします。

1.5 ロケールを設定

/etc/sysconfig/i18n
LANG="ja_JP.UTF8"
SYSFONT="latarcyrheb-sun16"

【注意】
この設定は、postgresqlのデータベースクラスタ初期化(initdb)時に、
エンコーディングを指定する際に必要になります。

1.6 サーバ再起動

サーバを再起動します。

shutdown -Fr now

1.7 sudoした際に元のユーザでのエージェントフォワードを可能にする

visudo
Defaults   env_keep += SSH_AUTH_SOCK

を追加

1.8 SElinuxをOFFに

vi /etc/sysconfig/selinux
SELINUX=disabled

に変更

2. ミドルウェアのインストール

apache、postgresqlなどをインストールします。

yum -y install httpd httpd-devel
yum -y install postgresql postgresql-devel postgresql-server

phpをインストールします

yum -y install php
yum -y install php-mbstring
yum -y install php-pgsql

その他モジュールをインストールします:

yum -y install curl-devel
yum -y install openssl openssl-devel
yum -y install subversion
yum -y install zlib-devel
yum -y install telnet mlocate

分けてあるのが面倒な人へ:

yum -y install httpd httpd-devel postgresql postgresql-devel postgresql-server php php-mbstring php-pgsql curl-devel openssl openssl-devel subversion zlib-devel telnet mlocate

2.1 postgresqlの設定

2.1.1 データベースクラスタの初期化

service postgresql initdb

過去には次のようにしていましたが、CentOSのお作法にのっとってないので変更しました:

old.sh
sudo -u postgres /usr/bin/initdb --encoding=UTF8 -D /var/lib/pgsql/data/

2.1.2 pg_hba.confの変更

pg_hba.conf(変更前)
# "local" is for Unix domain socket connections only
local   all         all                               ident
# IPv4 local connections:
host    all         all         127.0.0.1/32          ident
pg_hba.conf(変更後)
# "local" is for Unix domain socket connections only
local   all         all                               trust
# IPv4 local connections:
host    all         all         127.0.0.1/32          trust

2.1.2.1 postgresqlの起動

service postgresql start

2.1.3 データベースの作成

/usr/bin/createdb -U postgres -p 5432 -E UTF8 db_production
/usr/bin/createdb -U postgres -p 5432 -E UTF8 db_test

3 php.iniの設定

/etc/php.ini
date.timezone = Asia/Tokyo

4 apacheの設定

4.1 バーチャルホストの設定

NameVirtualHostのコメントを外します:

/etc/httpd/conf/httpd.conf
NameVirtualHost *:80

4.2 シグネチャをOFFにする:

セキュリティ対策の1つとして、シグネチャをOFFにします:

/etc/httpd/conf/httpd.conf
ServerSignature Off

4.3 AllowOverrideをAllに変更

/var/www/html以下でRewriteRuleを使えるようにAllowOverrideをAllに変更します:

<Directory "/var/www/html">

#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
    Options Indexes FollowSymLinks

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride All

4.4 バーチャルホスト用のconfファイルを設置

次のファイルを/etc/httpd/conf.dに設置します:

<VirtualHost *:80>
    ServerAdmin   root@localhost
    DocumentRoot  /var/www/html/app
    ServerName    ホスト名
    ErrorLog      logs/error_log
    CustomLog     logs/access_log common
</VirtualHost>

4.4.1 Document Rootの作成

mkdir /var/www/html/app

4.5 apache起動

service httpd start

5 cakephpのインストール

5.1 ダウンロード

cd /tmp
wget https://github.com/cakephp/cakephp/archive/2.6.7.zip
unzip 2.6.7.zip
cd cakephp-2.6.7
mv * /var/www/html
mv .htaccess /var/www/html
cd /var/www/html/app/
chown -R apache:apache ./tmp

5.2 core.phpの設定

/var/www/html/app/Config/core.php
 Configure::write('Security.salt', '40桁のランダムな文字列');
 Configure::write('Security.cipherSeed', 'ランダムな数字');
 Configure::write('Cake.logQuery', 1); # 意味は後述

5.3 database.phpの作成

datasourceにPostgresではなくPostgresLogと指定してください。
(SQLをファイルにログするためです、後述)

/var/www/html/app/Config/database.php
<?php
class DATABASE_CONFIG {

        public $default = array(
                'datasource' => 'Database/PostgresLog',
                'persistent' => false,
                'host'       => 'localhost',
                'port'       => '5432',
                'login'      => 'postgres',
                'password'   => '',
                'database'   => 'db_production',
                'prefix'     => '',
                'encoding'   => 'utf8',
        );

        public $test = array(
                'datasource' => 'Database/PostgresLog',
                'persistent' => false,
                'host'       => 'localhost',
                'port'       => '5432',
                'login'      => 'postgres',
                'password'   => '',
                'database'   => 'db_test',
                'prefix'     => '',
                'encoding'   => 'utf8',
        );
}
?>

5.4 PostgresLog.phpの作成

mkdir /var/www/html/app/Model/Datasource/Database/
/var/www/html/app/Model/Datasource/Database/PostgresLog.php
<?php
App::uses('Postgres', 'Model/Datasource/Database');
class PostgresLog extends Postgres {
    function logQuery($sql, $params = array()) {
        parent::logQuery($sql);
        $logLevel = Configure::read('Cake.logQuery');
        switch ($logLevel):
        case 1:
            $this->log($sql, LOG_DEBUG);                // SQLクエリーのみ
            break;
        case 2:
            $this->log($this->_queriesLog, LOG_DEBUG);  // SQLの実行詳細
            break;
        endswitch;
    }
}
?>

5.5 DebugKitの導入

5.5.1 DebugKitのダウンロード

cd /tmp
wget https://github.com/cakephp/debug_kit/zipball/2.2
unzip 2.2
mv (展開後のディレクトリ名) DebugKit
mv DebugKit /var/www/html/app/Plugin

5.5.2 bootstrap.phpにDebugKitを追加

/var/www/html/app/Config/bootstrap.php
CakePlugin::load('DebugKit');

6. ミドルウェアの自動起動の設定(任意)

chkconfig httpd on
chkconfig postgresql on

7. .htaccessの改良(任意)

7.1 htdigestによる認証の追加(任意)

/var/www/html/app/.htaccess
AuthType     Digest
AuthName     "レルム名"
AuthUserFile /etc/httpd/conf/.htdigest
Require      valid-user

7.2 htdigestの作成(任意)

cd /etc/httpd/conf
htdigest -c ./.htdigest "レルム名" ダイジェスト認証のユーザ名

7.3 静的ファイルのキャッシュを防止(任意)

/var/www/html/app/.htaccess
<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

8. 動作確認

ブラウザを開き、URLを入力してみてください!

7
8
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
7
8