Ubuntu下PHP安全设置要点
保持系统和PHP及其依赖库的最新状态,是修复已知安全漏洞的核心措施。定期执行以下命令更新系统及PHP组件:
sudo apt update && sudo apt upgrade -y
安装PHP时,建议使用Ubuntu官方仓库的稳定版本(如php8.1、php8.2),避免使用过时或第三方仓库的高风险版本。
php.ini是PHP安全的核心配置文件,需重点调整以下参数:
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
disable_functions = eval,exec,system,passthru,shell_exec,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
allow_url_fopen和allow_url_include,防止通过URL访问远程文件(如恶意脚本)。allow_url_fopen = Off
allow_url_include = Off
upload_max_filesize = 2M
post_max_size = 8M
file_uploads = On
HttpOnly(防止XSS窃取Cookie)和Secure(仅HTTPS传输)标志增强会话安全性。session.cookie_httponly = On
session.cookie_secure = On
session.gc_maxlifetime = 1440 # 会话有效期(分钟)
max_execution_time = 30
memory_limit = 128M
open_basedir限定PHP脚本可访问的目录范围,避免越权访问系统文件。open_basedir = /var/www/html:/tmp
expose_php,防止攻击者通过HTTP头获取PHP版本信息(针对性攻击)。expose_php = Off
/etc/apache2/apache2.conf或虚拟主机配置中添加:ServerTokens Prod
ServerSignature Off
/admin):<Directory /var/www/html/admin>
Order Deny,Allow
Deny from all
Allow from 192.168.1.100 # 替换为合法IP
</Directory>
mod_security(Web应用防火墙)和mod_evasive(防暴力破解)增强防护:sudo a2enmod security2
sudo a2enmod evasive2
sudo systemctl restart apache2
fastcgi_pass指向PHP-FPM套接字:/etc/nginx/sites-available/default中添加:location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 替换为实际PHP版本
}
.env、wp-config.php):location ~ /\.(?!well-known).* {
deny all;
}
/var/www/html)的所有者为Web服务器用户(通常为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 {} \;
/var/www/html/uploads)的脚本执行权限,防止上传的恶意文件被执行:sudo chmod -R 755 /var/www/html/uploads
sudo chown -R www-data:www-data /var/www/html/uploads
使用Let’s Encrypt免费SSL证书启用HTTPS,加密客户端与服务器之间的数据传输(防止中间人攻击)。执行以下命令:
sudo apt install certbot python3-certbot-apache # Apache
# 或
sudo apt install certbot python3-certbot-nginx # Nginx
sudo certbot --apache # Apache自动配置
# 或
sudo certbot --nginx # Nginx自动配置
证书到期前(通常90天)自动续期,无需手动操作。
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo apt install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
htmlspecialchars()函数转义特殊字符(如<、>),防止XSS攻击。echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
composer update更新依赖库,并通过composer audit扫描已知漏洞。error_log参数)和Web服务器访问日志(Apache:access.log/error.log;Nginx:access.log/error.log),定期检查日志中的异常行为(如大量404请求、SQL错误)。