确保系统和PHP为最新版本,修复已知安全漏洞:

sudo yum update -ysudo yum install epel-release -ysudo yum install php php-cli php-fpm php-mysqlnd php-gd php-mbstring php-xml php-pear php-bcmath -y编辑PHP-FPM主配置文件(通常为/etc/php-fpm.d/www.conf),调整以下参数:
root运行PHP进程,推荐使用apache或nginx用户。user = apachegroup = apachedisable_functions = eval,assert,system,shell_exec,passthru,exec,popen,curl_exec,curl_multi_exec,parse_ini_file,show_sourcepm.max_children = 50pm.start_servers = 5pm.min_spare_servers = 5pm.max_spare_servers = 35request_terminate_timeout = 60s修改后重启PHP-FPM:
sudo systemctl restart php-fpm编辑主配置文件/etc/php.ini,重点设置以下安全选项:
display_errors = Offlog_errors = Onerror_log = /var/log/php_errors.logfile_uploads = Onupload_max_filesize = 10Mpost_max_size = 10Msession.cookie_httponly = On# 禁止JavaScript访问会话Cookiesession.cookie_secure = On# 仅通过HTTPS传输Cookie(需开启HTTPS)session.cookie_samesite = Strict# 防止跨站请求伪造(CSRF)session.gc_maxlifetime = 1440 # 会话有效期(分钟)password_hash_default = bcryptallow_url_fopen = Offallow_url_include = Offopcache.enable = 1opcache.memory_consumption = 128opcache.interned_strings_buffer = 8opcache.max_accelerated_files = 4000opcache.revalidate_freq = 60opcache.fast_shutdown = 1根据使用的Web服务器(Apache/Nginx)调整配置:
编辑虚拟主机配置文件(如/etc/httpd/conf.d/your_site.conf),限制目录访问:
<Directory "/var/www/html">Options -Indexes +FollowSymLinks# 禁止目录列表AllowOverride AllRequire all granted</Directory>重启Apache:
sudo systemctl restart httpd编辑虚拟主机配置文件(如/etc/nginx/conf.d/your_site.conf),防止恶意文件访问:
server {listen 80;server_name example.com;root /var/www/html;index index.php index.html;location / {try_files $uri $uri/ =404;}location ~ .php$ {include snippets/fastcgi-php.conf;fastcgi_pass unix:/run/php-fpm/www.sock;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;include fastcgi_params;}location ~ /.ht {deny all;# 禁止访问.htaccess等隐藏文件}}重启Nginx:
sudo systemctl restart nginx使用firewalld限制对Web服务的访问,仅允许HTTP(80)和HTTPS(443)端口:
sudo firewall-cmd --permanent --zone=public --add-service=httpsudo firewall-cmd --permanent --zone=public --add-service=httpssudo firewall-cmd --reload安装并配置ModSecurity(开源Web应用防火墙),防御SQL注入、XSS等常见攻击:
sudo yum install mod_security -ysudo systemctl enable mod_securitysudo systemctl start mod_securityrsync或mysqldump)。/var/log/php_errors.log和Web服务器日志,发现异常行为。755目录、644文件),避免敏感文件(如config.php)被篡改:sudo chmod -R 755 /var/www/htmlsudo chown -R apache:apache /var/www/html# 根据实际用户调整通过以上步骤,可显著提升CentOS上PHP应用的安全性,防范常见攻击(如SQL注入、XSS、文件上传漏洞等)。需根据实际业务场景调整参数(如上传文件大小、会话有效期),并在测试环境验证配置有效性。