【Laravel】本番デプロイのgit使用と公開ディレクトリと分離

PHP

はじめに

開発が完了し、いよいよ本番公開をしてみます。
webサーバーはapacheを使用し、更に公開ディレクトリをLaravel本体と分離させてみます。
今回は別サーバーへの移行も考慮して、gitを使用しました。

今回のディレクトリ環境

・laravelテスト用
/home/laravel_user/test

・laravel本番用
/var
|
|—-www
| |
| |—-laravel_prj → 本番用ディレクトリ
| |
| |—-html
| | |
| | |—-laravel_open → 公開用ディレクトリ

・git用
/home/laravel_user/repos.git

手順

テスト用からgitリポジトリを作成

1:リポジトリを作成
テスト用ディレクトリ直下にて
git init

2:インデックスへの登録とコミット
git add .
git commit -m ‘hoken commit-1’

3:テスト用直下にgit用ディレクトリを作成
mkdir repos.git
cd repos.git
git init –bare –shared

4:リモートリポジトリへの登録と書き込み
テスト用ディレクトリへ移動後
git remote add origin ../repos.git
(fatal: remote origin already exists.と表示された場合は
git remote rm originでクリアする)

git push origin master:master

本番用ディレクトリへのクローンと設定

1:クローン
git clone /home/laravel_user/repos.git /var/www/prj

2:本番用ディレクトリの環境設定
.envを、テスト用ディレクトリからコピーし、ライブラリのインストールを行う。
composer install

3:.envを本番環境に合わせ修正
(最低限、APP_ENV,APP_DEBUG,APP_URLの3項目は変更)

4:アプリケーションキーの設定及びマイグレーション
php artisan key:generate
php artisan migrate:fresh

公開用ディレクトリの設定

1:公開用ディレクトリの設定
本番ディレクトリのpublic配下を公開ディレクトリへ移動
mv /var/www/laravel_prj/public /var/www/html/laravel_open

2:パスの変更
公開用ディレクトリから、本番用ディレクトリまでのパスをindex.phpに指定する

autoload.phpまでのパスを変更

require __DIR__.'/../../laravel_prj/vendor/autoload.php';

app.phpまでのパスを変更

$app = require_once __DIR__.'/../../laravel_prj/bootstrap/app.php';

Laravel本体の設定変更

1:Laravelのドキュメントルートを変更する為、クラスを新規作成する。
app/Prefdir.phpを以下の内容で新規作成

<?php
    namespace App;

    class Prefdir extends \Illuminate\Foundation\Application
    {
        public function publicPath()
        {
            return '/var/www/html/laravel_open';
        }
    }

bootstrap/app.phpを以下の内容に変更

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(DIR)
);
 ↓
$app = new App\Prefdir(
    realpath(DIR.'/../')
);

server.phpを以下の内容に変更

if ($uri !== '/' && file_exists(DIR.'/public'.$uri)) {
     return false;
}

require_once DIR.'/public/index.php';
↓
if ($uri !== '/' && file_exists('/var/www/html/laravel_open'.$uri)) {
     return false;
}

require_once '/var/www/html/laravel_open/index.php';

まとめ

gitを使用すれば、ディレクトリ移動や物理的な引っ越しなどの移動も簡単に行えそうです。
Laravel本体と公開ディレクトリの分離については、安全面や管理上から考慮して行うといいと思います。

コメント