PHP-FPM与Nginx如何在Linux上协同

作者:袖梨 2026-07-24

PHP-FPM(FastCGI Process Manager)和Nginx是两个常用的Web服务器组件,它们可以协同工作以提供高性能的PHP应用程序服务。以下是在Linux上配置PHP-FPM与Nginx协同工作的基本步骤:

PHP-FPM与Nginx在Linux上如何协同

1. 安装Nginx和PHP-FPM

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

在Debian/Ubuntu上:

sudo apt updatesudo apt install nginx php-fpm

在CentOS/RHEL上:

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

2. 配置PHP-FPM

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

编辑 /etc/php/版本号/fpm/pool.d/www.conf 文件:

sudo nano /etc/php/版本号/fpm/pool.d/www.conf

找到以下行并修改:

listen = /run/php/php版本号-fpm.sock

3. 配置Nginx

Nginx需要配置一个location块来处理PHP请求,并将它们传递给PHP-FPM。

编辑Nginx的默认站点配置文件:

sudo nano /etc/nginx/sites-available/default

添加或修改以下内容:

server {listen 80;server_name your_domain.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/php版本号-fpm.sock;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;include fastcgi_params;}}

4. 启动和启用服务

启动并启用Nginx和PHP-FPM服务:

在Debian/Ubuntu上:

sudo systemctl start nginxsudo systemctl enable nginxsudo systemctl start php版本号-fpmsudo systemctl enable php版本号-fpm

在CentOS/RHEL上:

sudo systemctl start nginxsudo systemctl enable nginxsudo systemctl start php-fpmsudo systemctl enable php-fpm

5. 测试配置

确保Nginx和PHP-FPM都在运行,并且可以正确处理PHP请求。

访问你的域名或服务器IP地址,你应该能够看到PHP文件被正确解析和执行。

6. 防火墙设置

如果你使用的是防火墙(如ufw),确保开放HTTP(80)和HTTPS(443)端口:

sudo ufw allow 'Nginx Full'

7. 日志检查

如果遇到问题,检查Nginx和PHP-FPM的日志文件以获取更多信息:

  • Nginx错误日志:/var/log/nginx/error.log
  • PHP-FPM错误日志:/var/log/php版本号-fpm.log

通过以上步骤,你应该能够在Linux上成功配置PHP-FPM与Nginx协同工作,提供高性能的PHP应用程序服务。

相关文章

精彩推荐