插件窝 干货文章 Centos7安装PHP及Nginx的方法

Centos7安装PHP及Nginx的方法

PHP Nginx sudo bash 92    来源:    2025-04-25

CentOS 7 安装 PHP 及 Nginx 方法指南

准备工作

  1. 确保系统已更新:

    sudo yum update -y
    
  2. 安装 EPEL 仓库(Extra Packages for Enterprise Linux):

    sudo yum install epel-release -y
    

安装 Nginx

  1. 安装 Nginx:

    sudo yum install nginx -y
    
  2. 启动 Nginx 并设置开机启动:

    sudo systemctl start nginx
    sudo systemctl enable nginx
    
  3. 检查 Nginx 是否运行:

    sudo systemctl status nginx
    
  4. 配置防火墙允许 HTTP 和 HTTPS 流量:

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

安装 PHP

  1. 安装 PHP 及相关扩展(以 PHP 7.4 为例):

    sudo yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
    sudo yum install -y yum-utils
    sudo yum-config-manager --enable remi-php74
    sudo yum install -y php php-fpm php-mysqlnd php-opcache php-gd php-xml php-mbstring php-json
    
  2. 启动 PHP-FPM 并设置开机启动:

    sudo systemctl start php-fpm
    sudo systemctl enable php-fpm
    
  3. 检查 PHP-FPM 状态:

    sudo systemctl status php-fpm
    

配置 Nginx 使用 PHP

  1. 编辑 Nginx 默认配置文件:

    sudo vi /etc/nginx/conf.d/default.conf
    
  2. 修改或添加以下内容(示例配置):

    server {
       listen       80;
       server_name  your_domain_or_ip;
       root         /usr/share/nginx/html;
    
       location / {
           index index.php index.html index.htm;
       }
    
       location ~ \.php$ {
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
           include        fastcgi_params;
       }
    }
    
  3. 测试 Nginx 配置:

    sudo nginx -t
    
  4. 重启 Nginx:

    sudo systemctl restart nginx
    

测试 PHP

  1. 创建测试 PHP 文件:

    echo "<?php phpinfo(); ?>" | sudo tee /usr/share/nginx/html/info.php
    
  2. 在浏览器中访问:

    http://your_server_ip/info.php
    

    应该能看到 PHP 信息页面。

可选配置

调整 PHP-FPM 配置

  1. 编辑 PHP-FPM 配置文件:

    sudo vi /etc/php-fpm.d/www.conf
    
  2. 确保以下设置正确:

    user = nginx
    group = nginx
    listen = 127.0.0.1:9000
    
  3. 重启 PHP-FPM:

    sudo systemctl restart php-fpm
    

安装其他 PHP 扩展

sudo yum install php-curl php-zip php-bcmath php-soap php-intl

设置目录权限

sudo chown -R nginx:nginx /usr/share/nginx/html
sudo chmod -R 755 /usr/share/nginx/html

故障排除

  1. 如果遇到 502 Bad Gateway 错误:

    • 检查 PHP-FPM 是否运行
    • 检查 /etc/php-fpm.d/www.conf 中的用户/组设置
    • 检查 Nginx 配置中的 fastcgi_pass 地址是否正确
  2. 查看日志:

    sudo tail -f /var/log/nginx/error.log
    sudo journalctl -xe
    
  3. SELinux 问题:

    sudo setsebool -P httpd_can_network_connect 1
    

按照以上步骤操作后,您应该已经在 CentOS 7 上成功安装了 Nginx 和 PHP,并配置它们协同工作。