【英文】Linux下搭建Nginx+PHP环境

Preface

Building Nginx+PHP environment on CentOS

Nginx Environment

Download Nginx

1
yum install -y nginx

Start Nginx

1
systemctl start nginx

Auto-start Nginx on boot

1
systemctl enable nginx

PHP Environment

Install RPM repository

1
2
rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

Install PHP and its components

1
yum -y install php72w php72w-cli php72w-common php72w-devel php72w-embedded php72w-fpm php72w-gd php72w-mbstring php72w-mysqlnd php72w-opcache php72w-pdo php72w-xml php72w-ldap

Start php-fpm

1
systemctl start php-fpm

Auto-start php-fpm on boot

1
systemctl enable php-fpm

Configure Nginx for Php

Copy Nginx configuration file

  • Copy a configuration file from the template to the conf.d directory
1
2
mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.back
cp /etc/nginx/nginx.conf.default /etc/nginx/nginx.conf

Modify the configuration file

  • Append index.php to line 45
/etc/nginx/nginx.conf
1
2
3
4
location / {
root html;
index index.html index.htm index.php;
}
  • Uncomment lines 65~71 related to php
/etc/nginx/nginx.conf
1
2
3
4
5
6
7
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}

Check the configuration file

1
/usr/sbin/nginx -t

Restart Nginx

1
systemctl restart nginx

Test

  • Create index.php in the root directory of the site
/usr/share/nginx/html
1
<?php phpinfo(); ?>

Troubleshooting

Error message

  • Accessing the page shows File not found.

Solution

  • Modify the value of fastcgi_param
/etc/nginx/nginx.conf
1
2
3
4
5
6
7
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

Done

  • Commemorative screenshot

References

Whitedba’s Blog
php中文网