插件窝 干货文章 CentOS7 下nginx与PHP如何安装以及配置

CentOS7 下nginx与PHP如何安装以及配置

PHP Nginx sudo 配置 128    来源:    2025-04-22

CentOS 7 下 Nginx 与 PHP 安装及配置指南

1. 系统准备

首先确保系统是最新的:

sudo yum update -y

2. 安装 Nginx

添加 EPEL 仓库

sudo yum install epel-release -y

安装 Nginx

sudo yum install nginx -y

启动并设置开机启动

sudo systemctl start nginx
sudo systemctl enable nginx

验证安装

在浏览器中访问服务器的IP地址,应该能看到Nginx欢迎页面。

3. 安装 PHP

添加 Webtatic 仓库(提供较新版本的PHP)

sudo rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

安装 PHP 7.4(可根据需要选择其他版本)

sudo yum install php74w php74w-fpm php74w-cli php74w-common php74w-mysqlnd php74w-mbstring php74w-gd php74w-xml -y

启动 PHP-FPM 并设置开机启动

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

4. 配置 Nginx 与 PHP-FPM

编辑 PHP-FPM 配置文件

sudo vi /etc/php-fpm.d/www.conf

找到并修改以下行:

user = nginx
group = nginx
listen = /var/run/php-fpm/php-fpm.sock
listen.owner = nginx
listen.group = nginx

重启 PHP-FPM

sudo systemctl restart php-fpm

配置 Nginx 处理 PHP 请求

编辑默认的 Nginx 配置文件:

sudo vi /etc/nginx/conf.d/default.conf

修改或添加以下内容:

server {
    listen       80;
    server_name  your_domain_or_ip;

    root   /usr/share/nginx/html;
    index  index.php index.html index.htm;

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

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

测试 Nginx 配置

sudo nginx -t

重启 Nginx

sudo systemctl restart nginx

5. 测试 PHP 配置

创建测试 PHP 文件:

sudo vi /usr/share/nginx/html/info.php

添加以下内容:

<?php phpinfo(); ?>

在浏览器中访问 http://your_server_ip/info.php,应该能看到 PHP 信息页面。

6. 安全配置(可选)

防火墙设置

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

SELinux 设置

sudo setsebool -P httpd_can_network_connect 1

7. 常见问题解决

  1. 502 Bad Gateway 错误

    • 检查 PHP-FPM 是否运行:systemctl status php-fpm
    • 检查 Nginx 和 PHP-FPM 的 socket 路径是否一致
    • 确保 /var/run/php-fpm/ 目录存在且有正确权限
  2. PHP 文件被下载而不是执行

    • 确保 Nginx 配置中正确处理了 PHP 文件
    • 检查 location ~ \.php$ 块是否正确配置
  3. 权限问题

    • 确保 Nginx 用户(通常是 nginx)对网站目录有读取权限
    • 确保 PHP-FPM 和 Nginx 使用相同的用户/组

通过以上步骤,您应该已经成功在 CentOS 7 上安装并配置了 Nginx 和 PHP。