LNMP (Linux + Nginx + MySQL + PHP) 加固详细指南

一、系统层加固

1.1 更新系统和软件

# Ubuntu / Debian
apt update && apt upgrade -y

# CentOS / Rocky Linux
yum update -y

1.2 设置防火墙

# Ubuntu / Debian
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable

# CentOS / Rocky Linux
firewall-cmd --permanent --set-default-zone=drop
firewall-cmd --permanent --zone=public --add-port=22/tcp
firewall-cmd --permanent --zone=public --add-port=80/tcp
firewall-cmd --permanent --zone=public --add-port=443/tcp
firewall-cmd --reload

1.3 配置 Fail2Ban

apt install fail2ban -y
# 或
yum install fail2ban -y

systemctl enable fail2ban
systemctl start fail2ban

1.4 禁用 root 远程登录

编辑 /etc/ssh/sshd_config:

PermitRootLogin no
PasswordAuthentication no

二、Nginx 加固

2.1 隐藏版本号

server_tokens off;

2.2 启用 HTTPS 并强制跳转

apt install certbot python3-certbot-nginx -y
certbot --nginx
server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$host$request_uri;
}

2.3 添加安全头

add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header Referrer-Policy no-referrer-when-downgrade;
add_header Content-Security-Policy "default-src 'self';";
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";

2.4 限制请求大小

client_max_body_size 2M;

2.5 限速和连接数控制

limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_conn conn_limit_per_ip 10;

limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;
limit_req zone=req_limit_per_ip burst=10;

三、MySQL 加固

3.1 修改 root 密码

mysql_secure_installation

3.2 只给本地连接

编辑 /etc/mysql/my.cnf/etc/my.cnf

bind-address = 127.0.0.1

3.3 权限最小化

CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'yourpassword';
GRANT SELECT, INSERT, UPDATE, DELETE ON yourdb.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;

3.4 日志察筛(可选)

启用察筛日志监控异常操作。


四、PHP 加固

4.1 修改 php.ini

expose_php = Off

display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log

disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

4.2 限制上传大小

upload_max_filesize = 2M
post_max_size = 8M

4.3 限制 Open_basedir

fastcgi_param PHP_ADMIN_VALUE "open_basedir=/var/www/html:/tmp/";

五、其他建议

  • 定期备份数据和网站文件

  • 安装监控工具(Netdata、Prometheus)

  • 使用 WAF (如 Cloudflare 或自建 WAF)

  • 部署 IDS/IPS (如 Snort)


本指南适合各种环境使用,可根据自身情况选择性加固。

你可能感兴趣的:(linux,nginx,mysql)