温馨提示×

php-fpm与nginx如何协同工作centos

小樊
42
2025-09-24 04:25:57
栏目: 编程语言

在CentOS系统中,PHP-FPM(FastCGI Process Manager)和Nginx可以协同工作来处理PHP请求。以下是配置这两个服务以协同工作的步骤:

1. 安装Nginx和PHP-FPM

首先,确保你的系统是最新的:

sudo yum update -y

然后安装Nginx和PHP-FPM:

sudo yum install nginx php-fpm -y

2. 启动并启用Nginx和PHP-FPM服务

启动Nginx和PHP-FPM服务,并设置它们在系统启动时自动启动:

sudo systemctl start nginx
sudo systemctl enable nginx

sudo systemctl start php-fpm
sudo systemctl enable php-fpm

3. 配置PHP-FPM

编辑PHP-FPM的配置文件 /etc/php-fpm.d/www.conf,确保监听地址和端口正确:

listen = /run/php-fpm/www.sock
listen.owner = nginx
listen.group = nginx
user = nginx
group = nginx

4. 配置Nginx

编辑Nginx的默认站点配置文件 /etc/nginx/conf.d/default.conf,添加或修改以下内容以处理PHP请求:

server {
    listen       80;
    server_name  localhost;

    root   /usr/share/nginx/html;
    index  index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    # 处理PHP文件
    location ~ \.php$ {
        fastcgi_pass   unix:/run/php-fpm/www.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # 其他配置...
}

5. 重启Nginx和PHP-FPM服务

应用配置更改后,重启Nginx和PHP-FPM服务:

sudo systemctl restart nginx
sudo systemctl restart php-fpm

6. 测试配置

创建一个简单的PHP文件来测试配置是否正确。在 /usr/share/nginx/html 目录下创建一个名为 info.php 的文件,内容如下:

<?php
phpinfo();
?>

然后在浏览器中访问 http://your_server_ip/info.php,如果看到PHP信息页面,说明配置成功。

7. 防火墙配置

确保防火墙允许HTTP和HTTPS流量:

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

通过以上步骤,你就可以在CentOS系统上成功配置Nginx和PHP-FPM协同工作来处理PHP请求。

0