以下是在 CentOS 系统上安装 PHP 7.4 和 Nginx 的详细步骤:
确保系统是最新的:
sudo yum update -y
安装 EPEL 仓库:
sudo yum install epel-release -y
安装 Nginx:
sudo yum install nginx -y
启动并设置开机自启 Nginx:
sudo systemctl start nginx
sudo systemctl enable nginx
检查 Nginx 是否运行:
sudo systemctl status nginx
防火墙设置(如果启用了防火墙):
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
添加 Remi 仓库(提供较新的 PHP 版本):
sudo yum install -y http://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum-config-manager --enable remi-php74
安装 PHP 7.4 和常用扩展:
sudo yum install -y php php-common php-opcache php-mcrypt php-cli php-gd php-curl php-mysqlnd php-fpm
验证 PHP 版本:
php -v
启动并设置开机自启 PHP-FPM:
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
编辑 Nginx 默认配置文件:
sudo vi /etc/nginx/conf.d/default.conf
修改或添加以下内容(替换原有 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;
}
}
测试 Nginx 配置:
sudo nginx -t
重启 Nginx:
sudo systemctl restart nginx
创建测试 PHP 文件:
echo "<?php phpinfo(); ?>" | sudo tee /usr/share/nginx/html/info.php
在浏览器中访问:
http://your_server_ip/info.php
你应该能看到 PHP 信息页面,确认 PHP 7.4 已正确安装并与 Nginx 集成。
限制 PHP 信息显示:
sudo sed -i 's/expose_php = On/expose_php = Off/' /etc/php.ini
删除测试文件:
sudo rm /usr/share/nginx/html/info.php
重启 PHP-FPM 使更改生效:
sudo systemctl restart php-fpm
现在你已经成功在 CentOS 上安装了 PHP 7.4 和 Nginx,并完成了基本配置。