在 CentOS 上配置 PHP 时,有几个常见但容易踩坑的点,下面按“系统环境 → PHP 安装 → 配置 → 安全 → 常见问题”给你梳理一下。
cat /etc/centos-release
✅ 推荐:使用 Remi 仓库 安装新版本 PHP(7.4 / 8.1 / 8.2)
yum install php
(版本旧、扩展少)
yum install epel-release
yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum install yum-utils
yum-config-manager --enable remi-php82
yum install php php-cli php-fpm php-mysqlnd php-mbstring php-xml php-gd
| 模式 | 说明 |
|---|---|
| php-fpm | ✅ 推荐(Nginx / Apache 都可用) |
| mod_php | Apache 专用,已不推荐 |
| CGI | 很少用 |
✅ Nginx + PHP-FPM 是标准组合
路径通常在:
/etc/php.ini
/etc/php-fpm.d/www.conf
expose_php = Off
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 30
max_input_time = 60
memory_limit = 128M
date.timezone = Asia/Shanghai
user = nginx
group = nginx
(Nginx 和 PHP-FPM 用户要一致)
listen = /run/php-fpm/php-fpm.sock
或
listen = 127.0.0.1:9000
⚠️ Nginx 配置要对应:
fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
getenforce
如果是 Enforcing,可能 PHP 无法写文件:
setsebool -P httpd_can_network_connect on
setsebool -P httpd_unified on
或临时关闭(不推荐):
setenforce 0
firewall-cmd --permanent --add-service=http
firewall-cmd --reload
chown -R nginx:nginx /var/www/html
chmod -R 755 /var/www/html
⚠️ 不要 777 全开,有安全风险
tail -f /var/log/php_errors.log
/var/log/php-fpm/error.log
/var/log/nginx/error.log
| 问题 | 原因 |
|---|---|
| 502 Bad Gateway | PHP-FPM 没启动 / sock 路径错 |
| 空白页 | display_errors 关了 |
| 上传失败 | upload_max_filesize 太小 |
| 权限拒绝 | SELinux / 文件属主错误 |
✅ CentOS 上配置 PHP 的核心要点:
如果你能告诉我:
我可以直接给你一套可复制的配置示例。