ubuntu

ubuntu下php-fpm与nginx如何配合

小樊
50
2025-08-07 12:18:41
栏目: 编程语言

在Ubuntu系统下,PHP-FPM(FastCGI Process Manager)与Nginx配合使用可以实现高效的PHP网站和应用服务。以下是配置步骤:

1. 安装Nginx和PHP-FPM

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

sudo apt update
sudo apt upgrade

然后安装Nginx和PHP-FPM:

sudo apt install nginx php-fpm

2. 配置PHP-FPM

PHP-FPM的配置文件通常位于 /etc/php/7.x/fpm/pool.d/www.conf(这里的 7.x 是你的PHP版本)。你可以根据需要修改这个文件,例如设置监听的socket或端口。

如果你选择使用socket,配置如下:

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

如果你选择使用端口,配置如下:

listen = 127.0.0.1:9000

3. 配置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; # 如果使用socket
        # fastcgi_pass 127.0.0.1:9000; # 如果使用端口
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

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

4. 启动和启用服务

启动Nginx和PHP-FPM服务:

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

设置Nginx和PHP-FPM开机自启动:

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

5. 测试配置

创建一个简单的PHP文件来测试配置是否正确:

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

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

6. 安全配置

为了提高安全性,你可以进行以下配置:

通过以上步骤,你可以在Ubuntu系统下成功配置Nginx和PHP-FPM,实现高效的PHP网站和应用服务。

0
看了该问题的人还看了