温馨提示×

Linux php-fpm与Nginx如何配合使用

小樊
46
2025-11-10 16:18:53
栏目: 编程语言

在现代的Web架构中,Nginx和PHP-FPM(FastCGI Process Manager)经常被一起使用,以提供高性能的PHP应用服务。Nginx主要负责处理HTTP请求和静态内容,而PHP-FPM则负责处理PHP脚本的执行。以下是如何在Linux系统上配置Nginx和PHP-FPM配合使用的步骤:

1. 安装Nginx和PHP-FPM

首先,确保你的系统已经安装了Nginx和PHP-FPM。你可以使用包管理器来安装它们。

在Debian/Ubuntu上:

sudo apt update
sudo apt install nginx php-fpm

在CentOS/RHEL上:

sudo yum install epel-release
sudo yum install nginx php-fpm

2. 配置PHP-FPM

PHP-FPM的配置文件通常位于 /etc/php/版本号/fpm/pool.d/www.conf。你需要确保PHP-FPM监听的是Unix socket或者TCP socket。

使用Unix socket:

编辑 /etc/php/版本号/fpm/pool.d/www.conf 文件,找到 listen 行并修改为:

listen = /run/php/php7.4-fpm.sock

确保目录存在并且有正确的权限:

sudo mkdir -p /run/php
sudo chown www-data:www-data /run/php

使用TCP socket:

如果你更喜欢使用TCP socket,可以这样配置:

listen = 127.0.0.1:9000

3. 配置Nginx

编辑Nginx的配置文件,通常位于 /etc/nginx/nginx.conf/etc/nginx/sites-available/默认

示例配置:

server {
    listen 80;
    server_name example.com;

    root /var/www/html;
    index index.php index.html index.htm;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock; # 或者使用 tcp:127.0.0.1:9000
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

4. 启动和启用服务

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

在Debian/Ubuntu上:

sudo systemctl start nginx
sudo systemctl start php7.4-fpm
sudo systemctl enable nginx
sudo systemctl enable php7.4-fpm

在CentOS/RHEL上:

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

5. 测试配置

最后,测试Nginx和PHP-FPM的配置是否正确。你可以通过访问你的服务器IP地址或域名来检查是否能够正确显示PHP页面。

curl http://your_server_ip_or_domain

如果一切配置正确,你应该能够看到PHP脚本的输出。

总结

通过以上步骤,你已经成功配置了Nginx和PHP-FPM在Linux系统上的配合使用。Nginx负责处理HTTP请求和静态内容,而PHP-FPM则负责处理PHP脚本的执行,从而提供高性能的Web服务。

0