linux

Linux PHP-FPM与Nginx如何搭配使用

小樊
37
2025-07-23 13:05:57
栏目: 编程语言

在现代Web应用架构中,Linux、PHP-FPM(FastCGI Process Manager)和Nginx的搭配使用是非常常见的组合。这种组合能够提供高性能、高可靠性和可扩展性。以下是如何在Linux系统上配置Nginx和PHP-FPM的步骤:

1. 安装Nginx

首先,你需要在你的Linux系统上安装Nginx。以下是在基于Debian的系统(如Ubuntu)上的安装命令:

sudo apt update
sudo apt install nginx

在基于Red Hat的系统(如CentOS)上的安装命令:

sudo yum install epel-release
sudo yum install nginx

2. 安装PHP-FPM

接下来,安装PHP-FPM。以下是在基于Debian的系统上的安装命令:

sudo apt install php-fpm

在基于Red Hat的系统上的安装命令:

sudo yum install php-fpm

3. 配置PHP-FPM

编辑PHP-FPM的配置文件,通常位于/etc/php/7.x/fpm/pool.d/www.conf(其中7.x是你的PHP版本)。确保以下配置项正确:

; 监听的socket文件路径
listen = /run/php/php7.x-fpm.sock

; 监听的TCP端口(可选)
; listen = 127.0.0.1:9000

; 用户和组
user = www-data
group = www-data

; PM模式(推荐使用dynamic)
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

4. 配置Nginx

编辑Nginx的默认站点配置文件,通常位于/etc/nginx/sites-available/default。以下是一个基本的配置示例:

server {
    listen 80;
    server_name example.com www.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.x-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

5. 启动和启用服务

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

在基于Debian的系统上:

sudo systemctl start nginx
sudo systemctl enable nginx

sudo systemctl start php7.x-fpm
sudo systemctl enable php7.x-fpm

在基于Red Hat的系统上:

sudo systemctl start nginx
sudo systemctl enable nginx

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

6. 测试配置

最后,测试Nginx和PHP-FPM的配置是否正确。你可以通过访问你的网站来检查是否能够正常显示PHP页面。

curl http://example.com

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

总结

通过以上步骤,你已经成功地在Linux系统上配置了Nginx和PHP-FPM。这种组合能够提供高性能的Web服务,并且易于扩展和维护。

0
看了该问题的人还看了