在现代Web开发中,PHP与Nginx的结合日益流行,能够打造高性能且稳定的服务器环境。本文将带你一步步完成在CentOS系统上安装PHP与Nginx的过程,助你快速搭建灵活的Web服务。
安装前请确保系统已升级至最新版本,运行以下命令完成更新:
<span class="fun">sudo yum update</span>
为便于安装最新版本的PHP,需要先添加EPEL和Remi软件源:
sudo yum install epel-release -y
sudo yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm -y
执行下列命令启用PHP 8.1版本仓库,当然你也可以根据需求启用其他版本:
<span class="fun">sudo yum-config-manager --enable remi-php81</span>
接下来安装PHP以及常见的扩展包,满足大部分项目需求:
<span class="fun">sudo yum install php php-cli php-fpm php-mysqlnd php-xml php-mbstring -y</span>
安装完毕后,需要编辑PHP-FPM配置文件,确保服务使用nginx用户运行:
<span class="fun">sudo vi /etc/php-fpm.d/www.conf</span>
将以下配置修改为:
user = nginx
group = nginx
通过yum安装Nginx:
<span class="fun">sudo yum install nginx -y</span>
sudo systemctl start nginx
sudo systemctl enable nginx
创建或编辑Nginx配置文件,加入对PHP的支持:
<span class="fun">sudo vi /etc/nginx/conf.d/default.conf</span>
添加以下内容:
server {
listen 80;
server_name your_domain.com; # 替换为你的域名或IP地址
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
创建一个简单的PHP测试文件以验证配置是否成功:
<span class="fun">echo "<?php phpinfo(); ?>" | sudo tee /usr/share/nginx/html/info.php</span>
在浏览器中访问 http://your_domain.com/info.php,如果看到PHP信息页面,说明PHP和Nginx已成功搭建。
按照以上步骤,你已经在CentOS系统上顺利安装并配置了PHP和Nginx,为Web开发环境打下坚实基础。希望本指南能帮助你快速掌握相关技能。