在CentOS上搭建PHP环境,你可以选择使用LAMP(Linux, Apache, MySQL, PHP)或LEMP(Linux, Nginx, MySQL, PHP)堆栈。以下是两种堆栈的搭建步骤:
LAMP堆栈搭建步骤:
-
更新系统:
sudo yum update -y
-
安装Apache:
sudo yum install httpd -y
-
启动并启用Apache服务:
sudo systemctl start httpd sudo systemctl enable httpd
-
安装MySQL:
sudo yum install mysql-server -y
-
启动并启用MySQL服务:
sudo systemctl start mysqld sudo systemctl enable mysqld
-
运行MySQL安全安装:
sudo mysql_secure_installation
-
安装PHP:
sudo yum install php php-mysql -y
-
重启Apache服务以加载PHP模块:
sudo systemctl restart httpd
-
测试PHP安装: 创建一个PHP文件
/var/www/html/phpinfo.php
,内容如下:然后在浏览器中访问
http://your_server_ip/phpinfo.php
,如果看到PHP信息页面,则安装成功。
LEMP堆栈搭建步骤:
-
更新系统:
sudo yum update -y
-
安装Nginx:
sudo yum install nginx -y
-
启动并启用Nginx服务:
sudo systemctl start nginx sudo systemctl enable nginx
-
安装MySQL:
sudo yum install mysql-server -y
-
启动并启用MySQL服务:
sudo systemctl start mysqld sudo systemctl enable mysqld
-
运行MySQL安全安装:
sudo mysql_secure_installation
-
安装PHP:
sudo yum install php-fpm php-mysql -y
-
配置PHP-FPM: 编辑
/etc/php-fpm.d/www.conf
文件,确保监听地址设置为Unix socket或者TCP/IP地址(例如127.0.0.1:9000)。 -
启动并启用PHP-FPM服务:
sudo systemctl start php-fpm sudo systemctl enable php-fpm
-
配置Nginx以使用PHP-FPM: 编辑Nginx的站点配置文件(通常位于
/etc/nginx/conf.d/default.conf
),添加以下内容:location ~ \.php$ { fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; # 或者使用TCP/IP地址 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
-
重启Nginx服务:
sudo systemctl restart nginx
-
测试PHP安装: 创建一个PHP文件
/var/www/html/phpinfo.php
,内容如下:然后在浏览器中访问
http://your_server_ip/phpinfo.php
,如果看到PHP信息页面,则安装成功。
以上步骤完成后,你就成功在CentOS上搭建了PHP环境。记得根据实际情况调整配置文件中的路径和参数。