插件窝 干货文章 Centos7 手动安装nginx+php环境

Centos7 手动安装nginx+php环境

PHP Nginx sudo bash 820    来源:    2025-05-11

CentOS 7 手动安装 Nginx + PHP 环境指南

准备工作

  1. 确保系统是最新的:
sudo yum update -y
  1. 安装必要的工具:
sudo yum install -y epel-release
sudo yum install -y wget unzip

安装 Nginx

  1. 安装 Nginx:
sudo yum install -y nginx
  1. 启动 Nginx 并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
  1. 检查 Nginx 是否正常运行:
curl -I 127.0.0.1

应该能看到 HTTP 200 响应

安装 PHP

  1. 添加 Webtatic 仓库(提供较新版本的 PHP):
sudo rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
  1. 安装 PHP 7.4 及其常用扩展(可根据需要选择其他版本):
sudo yum install -y php74w php74w-cli php74w-fpm php74w-common php74w-mysql php74w-mbstring php74w-gd php74w-xml php74w-opcache
  1. 启动 PHP-FPM 并设置开机自启:
sudo systemctl start php-fpm
sudo systemctl enable php-fpm

配置 Nginx 与 PHP-FPM

  1. 编辑 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
  1. 重启 PHP-FPM:
sudo systemctl restart php-fpm
  1. 配置 Nginx 支持 PHP:
sudo vi /etc/nginx/conf.d/default.conf

修改为以下内容(或添加 server 块):

server {
    listen       80;
    server_name  localhost;

    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;
    }
}
  1. 测试 Nginx 配置:
sudo nginx -t
  1. 重启 Nginx:
sudo systemctl restart nginx

测试 PHP

  1. 创建测试 PHP 文件:
sudo vi /usr/share/nginx/html/info.php

添加以下内容:

<?php phpinfo(); ?>
  1. 访问测试页面: 在浏览器中访问 http://your_server_ip/info.php,应该能看到 PHP 信息页面。

防火墙配置

如果启用了防火墙,需要开放 HTTP 端口:

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

可选配置

  1. 安装 Composer:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"
sudo mv composer.phar /usr/local/bin/composer
  1. 安装 MySQL/MariaDB(如果需要):
sudo yum install -y mariadb-server mariadb
sudo systemctl start mariadb
sudo systemctl enable mariadb
sudo mysql_secure_installation

现在你已经成功在 CentOS 7 上搭建了 Nginx + PHP 环境!