1. 及时更新系统与PHP版本
保持Ubuntu系统和PHP及相关库的最新状态,是修复已知安全漏洞的关键。定期运行以下命令更新系统:
sudo apt update && sudo apt upgrade -y
对于PHP,可通过sudo apt upgrade php*
升级所有PHP相关包,或使用PPA安装特定安全版本(如sudo add-apt-repository ppa:ondrej/php
)。
2. 配置PHP.ini核心安全参数
编辑PHP配置文件(路径如/etc/php/8.1/apache2/php.ini
或/etc/php/8.1/fpm/php.ini
),调整以下关键设置:
display_errors = Off log_errors = On error_log = /var/log/php_errors.log
allow_url_fopen = Off allow_url_include = Off
disable_functions = exec,system,passthru,shell_exec,proc_open,popen,curl_exec,eval,assert
open_basedir
约束PHP脚本仅能访问指定目录(如网站根目录),防止越权访问系统文件。open_basedir = /var/www/html:/tmp
max_execution_time = 30 max_input_time = 30 memory_limit = 64M
expose_php = Off
3. 强化Web服务器配置
autoindex
避免目录列表),重启服务使配置生效:sudo a2enmod php8.1 sudo a2dismod autoindex sudo systemctl restart apache2
fastcgi_pass
指向正确的PHP套接字(如unix:/var/run/php/php8.1-fpm.sock
),并限制仅处理.php
文件:location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; }
4. 安装安全模块与防火墙
sudo apt install libapache2-mod-security2 sudo a2enmod security2
配置规则集(如OWASP Core Rule Set)以增强防护。sudo ufw allow 'Apache Full' sudo ufw enable
sudo apt install fail2ban sudo systemctl start fail2ban && sudo systemctl enable fail2ban
5. 实施严格的文件与权限管理
www-data
),目录权限为755
(允许遍历),文件权限为644
(禁止写入):sudo chown -R www-data:www-data /var/www/html sudo find /var/www/html -type d -exec chmod 755 {} \; sudo find /var/www/html -type f -exec chmod 644 {} \;
<Directory "/var/www/html/uploads"> php_flag engine off Deny from all </Directory>
6. 采用安全编码与认证机制
<
, >
, '
, "
, \
),防止SQL注入和XSS攻击。$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch();
sudo apt install certbot python3-certbot-apache sudo certbot --apache -d yourdomain.com
7. 监控与日志分析
/var/log/apache2/error.log
)、PHP(/var/log/php_errors.log
)的错误日志,识别异常访问(如大量404错误、可疑POST请求)。fail2ban
、logwatch
或ELK Stack
(Elasticsearch+Logstash+Kibana)自动化日志分析,及时预警潜在攻击。