我是 Gemini-2.0-flash-exp 打造的 AI 助手,我的小脑袋瓜可厉害啦,帮你咻咻咻地概括文章重点!✨

本文档介绍了在 Ubuntu 18.04 系统上配置 PHP 环境的步骤,包括安装 Nginx、PHP 7.2、PHP-FPM 以及相关扩展。配置过程中,需要修改 PHP-FPM 的配置文件以提升安全性并调整连接数,同时配置 Nginx 将 PHP 请求转发给 PHP-FPM。文章还解释了 `fastcgi_params` 和 `fastcgi.conf` 的区别。最后,通过编写简单的 PHP 文件或使用 PHP 探针进行验证,确保环境配置成功。

实验环境

  • 操作系统:Ubuntu 18.04
  • Nginx:1.20.1
  • PHP:7.2.24
  • PHP-fpm:php7.2-fpm

实验步骤

安装程序包与依赖

# 更新软件包列表
apt update

# 安装程序包
apt install nginx
apt install php php-fpm php-xml php-json php-curl

# 安装常用依赖
sudo apt-get install php-json
sudo apt-get install php-curl
sudo apt-get install php-hash
sudo apt-get install php-openssl
sudo apt-get install php7.2-cgi

编辑fpm配置文件

sudo vim /etc/php/7.2/fpm/php.ini
# 提升安全性
# 修改参数如下:
# 778行 ;cgi.fix_fathinfo=1 更改为 cgi.fix_fathinfo=0

sudo vim /etc/php/7.2/fpm/pool.d/www.conf
# 配置连接数量
# 修改参数如下
#  36行 listen = 127.0.0.1:9000 
#  62行 listen.allowed_clients = 127.0.0.1
# 113行 pm.max_children = 50
# 139行 pm.max_requests = 500 
# 340行 request_terminate_timeout = 0 
# 344行 rlimit_files = 1024
# 以上部分,包括但不限于去除前面的";"

配置Nginx

sudo vim /etc/nginx/conf/nginx.conf # 富强后用/etc/nginx/conf/conf.d/xxx.conf
# 在index.html前面加入index.php
# 增加:
location ~ \.php$ {
    root           /home/wwwroot/;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_split_path_info  ^(.+\.php)(.*)$;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param  PATH_INFO $fastcgi_path_info;
    include        fastcgi_params; # include fastcgi.conf;
}

fastcgi_paramsfastcgi.conf 的区别:

  1. include fastcgi.confinclude fastcgi.conf; 通常用于包含 Nginx 默认提供的 FastCGI 配置参数文件。这个文件包含了一些通用的 FastCGI 参数设置,如 fastcgi_param、fastcgi_pass 等。这些参数适用于大多数 FastCGI 应用程序,包括 PHP、Python、Ruby 等。
  2. include fastcgi_paramsinclude fastcgi_params; 同样也是包含 FastCGI 配置参数的指令,但它通常比 fastcgi.conf 更加轻量级。fastcgi_params 文件包含了一些常见的 FastCGI 参数设置,同时避免了一些可能会引起安全问题的参数设置,如 SCRIPT_FILENAMEPATH_TRANSLATED 等。这使得 fastcgi_params 更适合用于共享主机环境或需要更严格安全设置的情况。

总的来说,两者的区别在于:

  • fastcgi.conf 可能包含更多的参数设置,适用于更多类型的 FastCGI 应用程序,但可能包含一些较为宽松的安全设置。
  • fastcgi_params 较为轻量,适用于较为安全和精简的配置需求,特别适合共享主机环境。

重启服务

sudo service php7.2-fpm restart # systemctl restart php7.2-fpm
sudo service nginx restart # systemctl restart nginx

验收

编写任意 php 文件,比如说简单的有 index.php:

<h1>
    <span> Hello, this is test page </span>
</h1>

或者 php 探针:

<?php 
	phpinfo(); 
?>

访问该 php 地址,得到正确的返回结果。完结,Move On!