在 Ubuntu 上搭建 LAMP(Linux + Apache + MySQL/MariaDB + PHP)环境后,安全加固是非常重要的一步。下面按“系统 → Apache → MySQL → PHP → 运维”几个层面,给你一套实用、可落地的方案。
sudo apt update
sudo apt upgrade -y
建议开启自动安全更新:
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
adduser deploy
usermod -aG sudo deploy
sudo ufw allow OpenSSH
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable
编辑:
sudo nano /etc/ssh/sshd_config
建议:
PermitRootLogin no
PasswordAuthentication no
Port 2222 # 可选
重启:
sudo systemctl restart ssh
sudo nano /etc/apache2/conf-available/security.conf
修改:
ServerTokens Prod
ServerSignature Off
确保:
Options -Indexes
例如:
<Directory /var/www/html/admin>
Require ip 123.123.123.123
</Directory>
使用 Let’s Encrypt:
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
sudo a2dismod autoindex status
sudo systemctl restart apache2
sudo mysql_secure_installation
建议:
不要用一个账号管所有库:
CREATE USER 'appuser'@'localhost' IDENTIFIED BY '强密码';
GRANT ALL PRIVILEGES ON appdb.* TO 'appuser'@'localhost';
sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf
bind-address = 127.0.0.1
编辑:
sudo nano /etc/php/*/apache2/php.ini
建议修改:
expose_php = Off
display_errors = Off
log_errors = On
allow_url_include = Off
disable_functions = exec,passthru,shell_exec,system,proc_open,popen
重启 Apache:
sudo systemctl restart apache2
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
上传目录(如 uploads)可单独控制写权限,但禁止执行 PHP。
sudo apt install fail2ban
sudo tail -f /var/log/apache2/access.log
sudo tail -f /var/log/auth.log
✅ 系统更新
✅ UFW 防火墙
✅ SSH 禁 root + 密钥登录
✅ Apache 隐藏版本
✅ HTTPS
✅ MySQL 专用用户
✅ PHP 关闭错误显示
✅ fail2ban
如果你愿意,可以告诉我:
我可以直接帮你生成一份可执行的加固脚本。