centos

php-fpm与nginx在centos如何联调

小樊
45
2025-11-17 18:47:30
栏目: 编程语言

要在 CentOS 上将 PHP-FPM 与 Nginx 配置为协同工作,你需要遵循以下步骤:

  1. 安装 Nginx 和 PHP-FPM: 使用 YUM(Yellowdog Updater, Modified)包管理器安装 Nginx 和 PHP-FPM。在终端中运行以下命令:

    sudo yum install epel-release
    sudo yum install nginx
    sudo yum install php-fpm
    
  2. 启动并设置 Nginx 和 PHP-FPM 服务: 使用 systemctl 启动并设置 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 行并确保其设置为以下内容:

    listen = /run/php-fpm/www.sock
    

    这将使 PHP-FPM 使用 Unix 套接字与 Nginx 通信。

  4. 配置 Nginx: 编辑 Nginx 配置文件 /etc/nginx/nginx.conf 或创建一个新的站点配置文件(例如 /etc/nginx/conf.d/yourdomain.conf),并添加以下内容:

    server {
        listen 80;
        server_name yourdomain.com; # 替换为你的域名或 IP 地址
    
        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-fpm/www.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
    

    这将配置 Nginx 以处理 PHP 请求并将它们传递给 PHP-FPM。

  5. 重启 Nginx 和 PHP-FPM 服务: 为了使更改生效,请重启 Nginx 和 PHP-FPM 服务:

    sudo systemctl restart nginx
    sudo systemctl restart php-fpm
    
  6. 测试配置: 在你的网站根目录(例如 /var/www/html)中创建一个名为 info.php 的文件,并添加以下内容:

    <?php
    phpinfo();
    ?>
    

    然后,在浏览器中访问 http://yourdomain.com/info.php。你应该看到 PHP 信息页面,表明 Nginx 和 PHP-FPM 已成功配置并协同工作。

  7. 安全性和性能优化: 根据需要调整 Nginx 和 PHP-FPM 的配置,以提高安全性和性能。例如,你可以限制允许访问的 IP 地址范围、配置缓存和压缩等。

完成以上步骤后,你应该已经成功地在 CentOS 上将 PHP-FPM 与 Nginx 配置为协同工作。

0
看了该问题的人还看了