バックエンドとフロントエンドを行き来するWEBプログラマ―のメモ帳

WEBプログラマ―。バックエンドはPHP, MySQL, CentOS系, フロントエンドはJavaScript, jQuery, HTML, CSSで仕事してます。

Laravelプロジェクトを本番サーバーで公開する時、Permission deniedでハマったら

The stream or file "/var/www/laravel/nekopic_website/storage/logs/laravel-2019-06-30.log" could not be opened: failed to open stream: Permission denied

f:id:mashiro_ruka:20190630110419p:plain

結論

権限の設定が必要

WEBサーバーを実行するapacheユーザーの権限が
logにないよ、ということでした。
さらに、Laravelのサイトにもある通り、
今後のためにstorageディレクトリと、bootstrap/cacheディレクトリにも権限を与えておく必要があります。

権限の設定法

こちらを参考に自分用にアレンジしました。

参考サイト

qiita.com

手順

まずはユーザーについてですが、以下のユーザーがいます
・hogeuser(puttyなどでログインしているユーザー)
sftpなどでファイル操作ができる
apache
webサーバーの実行ユーザー


Laravel用のユーザーグループを作成

sudo groupadd laravel

今作ったlaravelグループに、hogeuserとapacheを追加

sudo gpasswd -a hogeuser laravel
sudo gpasswd -a apache laravel

laravelプロジェクトに移動

cd /var/www/laravel/nekopic_website

パーミッションを、ディレクトリ:755、ファイル:644にする

sudo find ./ -type d -exec chmod 755 {} \;
sudo find ./ -type f -exec chmod 644 {} \;

所有グループを変更(エラーが修正される)

sudo chown -R :laravel ./storage
sudo chown -R :laravel ./bootstrap/cache

もう一度、storageとbootstrap/cache内のパーミッション
ディレクトリ:755、ファイル:644にする

sudo find ./storage -type d -exec chmod 775 {} \;
sudo find ./storage -type f -exec chmod 664 {} \;

sudo find ./bootstrap/cache -type d -exec chmod 775 {} \;
sudo find ./bootstrap/cache -type f -exec chmod 664 {} \;

SGIDを設定することにより、今後、storage内と、bootstrap/cache内で作成されたファイルやディレクトリの
所有グループはlaravelになるようにする。(logsのファイルは日ごとに作成されるため)

sudo find ./storage -type d -exec chmod g+s {} \;
sudo find ./bootstrap/cache -type d -exec chmod g+s {} \;

ACLのデフォルト設定で、
今後、storageとbootstrap/cache下にファイルやディレクトリが作られたら、
ディレクトリ:775、ファイル:664になる

sudo setfacl -R -d -m g::rwx ./storage
sudo setfacl -R -d -m g::rwx ./bootstrap/cache

再起動する

sudo shutdown -r now
重要!

サーバーを再起動したあと、忘れずにMySQLを再起動する。

sudo systemctl restart mysqld

そうしないと、ブラウザでアクセスした際に、
Connection refused (SQL: select count(*) as aggregate from
というエラーが出ます。

MySQL再起動は必ず行ってください。