温馨提示×

centos php配置要注意什么

小樊
43
2026-10-05 18:14:22
栏目: 编程语言

在 CentOS 上配置 PHP 时,有几个常见但容易踩坑的点,下面按“系统环境 → PHP 安装 → 配置 → 安全 → 常见问题”给你梳理一下。


一、系统环境与版本选择

1. 确认 CentOS 版本

cat /etc/centos-release
  • CentOS 7:PHP 默认 5.4(太老,不建议)
  • CentOS 8 / Stream:支持较新 PHP(但已停止维护,建议迁移到 Rocky / Alma)

✅ 推荐:使用 Remi 仓库 安装新版本 PHP(7.4 / 8.1 / 8.2)


二、PHP 安装方式(重要)

不推荐

yum install php

(版本旧、扩展少)

推荐(Remi 仓库)

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 运行模式选择

常见三种

模式 说明
php-fpm ✅ 推荐(Nginx / Apache 都可用)
mod_php Apache 专用,已不推荐
CGI 很少用

✅ Nginx + PHP-FPM 是标准组合


四、php.ini 关键配置

路径通常在:

/etc/php.ini
/etc/php-fpm.d/www.conf

1. 基础安全配置

expose_php = Off
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log

2. 上传与执行限制

upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 30
max_input_time = 60
memory_limit = 128M

3. 时区

date.timezone = Asia/Shanghai

五、PHP-FPM 配置注意点

1. 用户权限

user = nginx
group = nginx

(Nginx 和 PHP-FPM 用户要一致)

2. 监听方式

listen = /run/php-fpm/php-fpm.sock

或

listen = 127.0.0.1:9000

⚠️ Nginx 配置要对应:

fastcgi_pass unix:/run/php-fpm/php-fpm.sock;

六、SELinux 与防火墙(CentOS 特有坑)

SELinux

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 全开,有安全风险


八、日志排查

PHP 错误

tail -f /var/log/php_errors.log

PHP-FPM

/var/log/php-fpm/error.log

Nginx

/var/log/nginx/error.log

九、常见错误汇总

问题 原因
502 Bad Gateway PHP-FPM 没启动 / sock 路径错
空白页 display_errors 关了
上传失败 upload_max_filesize 太小
权限拒绝 SELinux / 文件属主错误

十、总结建议

✅ CentOS 上配置 PHP 的核心要点:

  1. 用 Remi 装新版本 PHP
  2. 使用 PHP-FPM
  3. 注意 SELinux 和权限
  4. 关闭错误显示,开启错误日志
  5. Nginx / PHP-FPM 用户一致

如果你能告诉我:

  • CentOS 版本
  • 用 Nginx 还是 Apache
  • PHP 版本需求

我可以直接给你一套可复制的配置示例。

0 踩