mockroNotes -モックロノート-

ガジェットやイラスト、ワークアウトに関心を示すブログです

LEMP環境の構築[PHPページを処理するためのNginxの設定]

f:id:mockro:20210616234213p:plain


 これで、必要なコンポーネントがすべてインストールされました。 Nginxが動的コンテンツのためにPHPを使うように設定していきます。

前回:



 ステップ9 - PHPページを処理するためのNginxの設定

nginxの設定はnginx自体の設定を行うためのnginx.confファイルと、バーチャルホストを設定するためのdefault.confに分かれています。ファイルは”/etc/nginx/”以下に保存されています。

nginx.confファイルの変更

まずは以下のようにnginx.confの変更を行います。

$ sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.org
$ sudo vim /etc/nginx/nginx.conf

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}

http {
    server_tokens off;
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  3;

    gzip  on;

    server_names_hash_bucket_size 128;

    include /etc/nginx/conf.d/*.conf;
    include sites-enabled/*.conf;
}

default.confの変更

バーチャルホストを設定するためのdefault.confを以下のように編集します。

$ sudo cp /etc/nginx/conf.d/default.conf etc/nginx/conf.d/default.conf.org
$ sudo vim /etc/nginx/conf.d/default.conf

server {
    listen       80;
    server_name  server_domain_name_or_IP;

    # note that these lines are originally from the "location /" block
    root   /usr/share/nginx/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Nginxを再起動して必要な変更をロードします。

$ sudo systemctl restart nginx

ステップ10 - Webサーバー上でPHP処理をテストする

システムがPHP用に正しく設定されていることをテストします。

$ sudo vim /usr/share/nginx/html/info.php

次のPHPコードをファイル内に配置します。

<?php phpinfo(); ?>

ブラウザからこのファイルにアクセスすることで、WebサーバーがPHPスクリプトによって生成されたコンテンツを正しく表示できるかどうかをテストできます。

 


参考にしたサイト