【笔记】Linux下搭建Nginx+PHP环境

前言

CentOS下搭建Nginx+PHP环境

Nginx环境

下载Nginx

1
yum install -y nginx

启动Nginx

1
systemctl start nginx

开机自启Nginx

1
systemctl enable nginx

PHP环境

安装rpm源

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

安装PHP及其组建

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

启动php-fpm

1
systemctl start php-fpm

开机自启php-fpm

1
systemctl enable php-fpm

Nginx配置Php

复制Nginx配置文件

  • 从配置文件模版复制一份到conf.d目录下
1
2
mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.back
cp /etc/nginx/nginx.conf.default /etc/nginx/nginx.conf

编辑配置文件

1
vim /etc/nginx/nginx.conf
  • 45行追加index.php

/etc/nginx/nginx.conf

1
2
3
4
location / {
root html;
index index.html index.htm index.php;
}
  • 解除65~71行关于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;
}

检查配置文件

1
/usr/sbin/nginx -t

重启Nginx

1
systemctl restart nginx

测试

  • 在站点根目录创建index.php

/usr/share/nginx/html

1
<?php phpinfo(); ?>

踩坑

报错

  • 访问页面显示File not found.

解决问题

  • 修改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;
}

完成

  • 截图纪念

参考文献

Whitedba’s Blog
php中文网