LoginSignup
4
5

More than 5 years have passed since last update.

[CentOS7] Nginx サーバーで PHP-FPM を使って PHP を実行させるための設定

Last updated at Posted at 2018-11-21

環境

CentOS: 7.4
PHP: 7.2
Nginx: 1.14

やりたいこと

Nginx サーバーの環境下で PHP を実行できるように設定を行います。

ルートディレクトリは /home/user_name/projects として設定します。
(ここは自分の好きなディレクトリを設定して問題ありません。)

前提条件

以下のインストールが完了していることを前提に設定を行います。

  • PHP
  • Nginx
  • PHP-FPM(NginxでPHPを実行するために必要)

インストール方法については【CentOS】PHP、PHP-FPM、NginX のインストールをご確認ください。

Nginx の設定

ポートの設定

/etc/nginx/conf.d/default.conf の設定ファイルを編集します。

Apache と同時起動したいので、Apach で指定しているポートは使用できません。
今回は Apache で 80 番を指定しているため、Nginx では 8080 番を利用します。

/etc/nginx/conf.d/default.conf
server {
    listen       8080;
    server_name  localhost;
    ...

PHP関連の設定

次に、Nginx で PHP が実行できるようにするための設定を行います。
設定するファイルは同じく /etc/nginx/conf.d/default.conf です。

初期設定では location ~ \.php$ {...} の全体がコメントアウトされているため外します。
また、rootfastcgi_param の部分にルートディレクトリを設定します。

/etc/nginx/conf.d/default.conf
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

    location ~ \.php$ {
        root           /home/user_name/projects;
        fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /home/user_name/projects$fastcgi_script_name;
        include        fastcgi_params;
    }

設定を反映させる

Nginx を起動(再起動)します。
ターミナルから以下のコマンドを入力して実行します。

$ sudo systemctl restart nginx

PHP-FPM の設定

user と group を nginx に変更します。
初期設定では apache となっているので、コメントアウト(もしくは削除)します。

/etc/php-fpm.d/www.conf
;user = apache
user = nginx

;group = apache
group = nginx

設定を反映させる

PHP-FPM を再起動します。
ターミナルから以下のコマンドを入力して実行します。

$ sudo systemctl restart nginx

Nginx で PHP を実行させる

実行用ファイルの作成

ルートディレクトリに index.php を作成します。
正しく設定できていれば、ルートディレクトリにアクセスしたとき Nginx が index.php を実行します。

/home/user_name/projects/index.php
<?php phpinfo(); ?>

PHP の実行

ブラウザのURLに localhost:8080 と入力して、以下の画面が表示されれば成功です(8080 は自分が設定した Nginx のポート番号)。
これはルートディレクトリ(/home/user_name/projects)の index.php が実行された結果です。

キャプチャ.PNG

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