插件窝 干货文章 LNMP服务器安全设置指南

LNMP服务器安全设置指南

安全 Nginx 配置 定期 269    来源:    2025-05-08

LNMP服务器安全设置指南

一、基础系统安全加固

  1. 系统更新

    • 定期执行:yum updateapt-get update && apt-get upgrade
    • 配置自动安全更新
  2. SSH安全

    # 修改默认端口
    Port 2222
    
    # 禁用root登录
    PermitRootLogin no
    
    # 使用密钥认证
    PasswordAuthentication no
    
    # 限制登录IP
    AllowUsers user@your_ip
    

    修改后重启SSH服务:service sshd restart

  3. 防火墙配置

    # 安装iptables/firewalld
    yum install firewalld
    systemctl enable firewalld
    systemctl start firewalld
    
    # 开放必要端口
    firewall-cmd --permanent --add-port=80/tcp
    firewall-cmd --permanent --add-port=443/tcp
    firewall-cmd --permanent --add-port=2222/tcp
    firewall-cmd --reload
    

二、Nginx安全配置

  1. 隐藏版本信息

    server_tokens off;
    
  2. 限制HTTP方法

    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
       return 444;
    }
    
  3. 防止点击劫持

    add_header X-Frame-Options "SAMEORIGIN";
    
  4. XSS防护

    add_header X-XSS-Protection "1; mode=block";
    
  5. 禁用目录浏览

    autoindex off;
    
  6. SSL安全配置

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';
    

三、MySQL安全配置

  1. 运行安全脚本

    mysql_secure_installation
    
  2. 修改默认端口

    # /etc/my.cnf
    [mysqld]
    port = 3307
    
  3. 限制访问IP

    GRANT ALL PRIVILEGES ON db.* TO 'user'@'192.168.1.%' IDENTIFIED BY 'password';
    
  4. 禁用远程root登录

    DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1');
    FLUSH PRIVILEGES;
    

四、PHP安全配置

  1. 禁用危险函数

    disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
    
  2. 限制文件访问

    open_basedir = /var/www/:/tmp/
    
  3. 关闭错误显示

    display_errors = Off
    log_errors = On
    
  4. 限制上传文件大小

    upload_max_filesize = 2M
    post_max_size = 8M
    

五、文件权限管理

  1. 网站目录权限

    chown -R nginx:nginx /var/www/
    find /var/www/ -type d -exec chmod 750 {} \;
    find /var/www/ -type f -exec chmod 640 {} \;
    
  2. 敏感文件保护

    chmod 600 /etc/nginx/nginx.conf
    chmod 600 /etc/my.cnf
    chmod 600 /etc/php.ini
    

六、日志与监控

  1. 启用日志

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    
  2. 日志轮转

    • 配置logrotate
    • 定期分析日志
  3. 安装监控工具

    # 如fail2ban
    yum install fail2ban
    systemctl enable fail2ban
    systemctl start fail2ban
    

七、定期维护

  1. 备份策略

    • 数据库定期备份
    • 网站文件备份
    • 配置备份
  2. 安全扫描

    # 使用lynis进行安全审计
    yum install lynis
    lynis audit system
    
  3. 漏洞监控

    • 订阅安全公告
    • 定期检查组件版本

通过以上配置,您的LNMP服务器将具备较高的安全防护能力。请根据实际业务需求调整配置,并定期检查和更新安全设置。