插件窝 干货文章 Centos怎么安装PHP7.4和Nginx

Centos怎么安装PHP7.4和Nginx

PHP Nginx sudo bash 296    来源:    2025-04-21

CentOS 安装 PHP 7.4 和 Nginx 指南

以下是在 CentOS 系统上安装 PHP 7.4 和 Nginx 的详细步骤:

准备工作

  1. 确保系统是最新的:

    sudo yum update -y
    
  2. 安装 EPEL 仓库:

    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. 防火墙设置(如果启用了防火墙):

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

安装 PHP 7.4

  1. 添加 Remi 仓库(提供较新的 PHP 版本):

    sudo yum install -y http://rpms.remirepo.net/enterprise/remi-release-7.rpm
    sudo yum-config-manager --enable remi-php74
    
  2. 安装 PHP 7.4 和常用扩展:

    sudo yum install -y php php-common php-opcache php-mcrypt php-cli php-gd php-curl php-mysqlnd php-fpm
    
  3. 验证 PHP 版本:

    php -v
    
  4. 启动并设置开机自启 PHP-FPM:

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

配置 Nginx 使用 PHP

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

    sudo vi /etc/nginx/conf.d/default.conf
    
  2. 修改或添加以下内容(替换原有 server 块):

    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;
       }
    
       error_page 404 /404.html;
       error_page 500 502 503 504 /50x.html;
    
       location = /50x.html {
           root /usr/share/nginx/html;
       }
    
       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;
       }
    }
    
  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 7.4 已正确安装并与 Nginx 集成。

可选:安全配置

  1. 限制 PHP 信息显示:

    sudo sed -i 's/expose_php = On/expose_php = Off/' /etc/php.ini
    
  2. 删除测试文件:

    sudo rm /usr/share/nginx/html/info.php
    
  3. 重启 PHP-FPM 使更改生效:

    sudo systemctl restart php-fpm
    

现在你已经成功在 CentOS 上安装了 PHP 7.4 和 Nginx,并完成了基本配置。