Nginx在Ubuntu上的安全配置指南
在配置Nginx前,需先强化Ubuntu系统的基础安全,降低整体风险:
sudo apt update && sudo apt upgrade -y,确保系统和Nginx等软件为最新版本,修补已知漏洞。/etc/ssh/sshd_config,将PermitRootLogin yes改为no,并重启SSH服务(sudo systemctl restart sshd),避免直接使用root账户登录。sudo ufw allow 22/tcp(SSH)、sudo ufw allow 80/tcp(HTTP)、sudo ufw allow 443/tcp(HTTPS)开放必要端口,然后执行sudo ufw enable启用防火墙,通过sudo ufw status验证状态。/etc/nginx/nginx.conf,在http块中添加server_tokens off;,防止攻击者通过响应头识别Nginx版本。server块中添加more_clear_headers Server;,进一步隐藏服务器信息(需安装headers-more-nginx-module模块,若未安装可通过源码编译添加)。/admin/),配置仅允许特定IP访问:location /admin/ {
allow 192.168.1.0/24; # 允许内部网络
allow 10.0.0.0/8; # 允许私有网络
deny all; # 拒绝其他所有IP
}
geo模块限制国家/地区访问(需提前配置IP数据库):http {
geo $country {
default 0; # 默认拒绝
192.168.1.0/24 1; # 允许国内IP段
}
server {
if ($country = 0) {
return 403; # 非允许地区返回403
}
}
}
http块中定义共享内存区域,限制单个IP的请求频率:http {
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s; # 每秒10个请求
server {
location / {
limit_req zone=mylimit burst=20 nodelay; # 允许突发20个请求,无延迟
}
}
}
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444; # 直接关闭连接
}
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
sudo apt install certbot python3-certbot-nginx),并配置强加密套件:server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3; # 仅使用TLS 1.2及以上
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'; # 强加密套件
ssl_prefer_server_ciphers on;
}
location / {
autoindex off; # 关闭目录列表
try_files $uri $uri/ =404; # 规范化路径,避免../遍历
}
client_max_body_size 10M; # 限制请求体为10MB
http块中定义共享内存区域,限制每个IP的并发连接数:http {
limit_conn_zone $binary_remote_addr zone=ops:10m; # 共享内存区域
server {
location / {
limit_conn ops 5; # 每个IP最多5个并发连接
}
}
}
sudo apt install fail2ban
编辑/etc/fail2ban/jail.d/nginx.conf:[nginx-http-auth]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
maxretry = 5
bantime = 3600
findtime = 600
重启Fail2Ban:sudo systemctl restart fail2ban。unattended-upgrades:sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
sudo tar -czvf nginx-backup-$(date +%F).tar.gz /etc/nginx /var/log/nginx
设置定时任务(每天凌晨2点备份):echo "0 2 * * * tar -czvf /backup/nginx-$(date +\%F).tar.gz /etc/nginx /var/log/nginx" | sudo tee -a /etc/crontab
/var/log/nginx/access.log)和错误日志(/var/log/nginx/error.log),使用grep、awk等工具分析异常请求(如大量404、403错误)。