Ubuntu下PHP安全设置要点

保持系统和PHP及其依赖库的最新状态,是修复已知安全漏洞的核心措施。定期执行以下命令更新系统及PHP组件:
sudo apt update && sudo apt upgrade -y安装PHP时,建议使用Ubuntu官方仓库的稳定版本(如php8.1、php8.2),避免使用过时或第三方仓库的高风险版本。
php.ini是PHP安全的核心配置文件,需重点调整以下参数:
display_errors = Offlog_errors = Onerror_log = /var/log/php_errors.logdisable_functions = eval,exec,system,passthru,shell_exec,popen,curl_exec,curl_multi_exec,parse_ini_file,show_sourceallow_url_fopen和allow_url_include,防止通过URL访问远程文件(如恶意脚本)。allow_url_fopen = Offallow_url_include = Offupload_max_filesize = 2Mpost_max_size = 8Mfile_uploads = OnHttpOnly(防止XSS窃取Cookie)和Secure(仅HTTPS传输)标志增强会话安全性。session.cookie_httponly = Onsession.cookie_secure = Onsession.gc_maxlifetime = 1440# 会话有效期(分钟)max_execution_time = 30memory_limit = 128Mopen_basedir限定PHP脚本可访问的目录范围,避免越权访问系统文件。open_basedir = /var/www/html:/tmpexpose_php,防止攻击者通过HTTP头获取PHP版本信息(针对性攻击)。expose_php = Off/etc/apache2/apache2.conf或虚拟主机配置中添加:ServerTokens ProdServerSignature Off/admin):<Directory /var/www/html/admin>Order Deny,AllowDeny from allAllow from 192.168.1.100# 替换为合法IP</Directory>mod_security(Web应用防火墙)和mod_evasive(防暴力破解)增强防护:sudo a2enmod security2sudo a2enmod evasive2sudo systemctl restart apache2fastcgi_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/htmlsudo 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/uploadssudo 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# Nginxsudo certbot --apache# Apache自动配置# 或sudo certbot --nginx# Nginx自动配置证书到期前(通常90天)自动续期,无需手动操作。
sudo ufw allow 80/tcpsudo ufw allow 443/tcpsudo ufw enablesudo apt install fail2bansudo systemctl enable fail2bansudo 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错误)。