# 检查当前Nginx版本
nginx -v
# 定期更新Nginx
sudo apt update && sudo apt upgrade nginx # Debian/Ubuntu
sudo yum update nginx # CentOS/RHEL
# 编译时只启用必要模块
./configure --without-http_autoindex_module --without-http_ssi_module
make && make install
# nginx.conf主配置
user nginx;
worker_processes auto;
pid /run/nginx.pid;
# 禁止worker进程以root运行
events {
worker_connections 1024;
}
# 限制特定目录访问
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
# 全局限制HTTP方法
limit_except GET POST {
deny all;
}
# 防止暴力破解
limit_req_zone $binary_remote_addr zone=auth:10m rate=5r/m;
location /login {
limit_req zone=auth burst=10 nodelay;
proxy_pass http://backend;
}
# 使用GeoIP模块
geo $blocked_country {
default 0;
CN 1;
RU 1;
}
server {
if ($blocked_country) {
return 403;
}
}
server {
listen 443 ssl http2;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_stapling on;
ssl_stapling_verify on;
# HSTS头(谨慎使用)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
}
# 使用Certbot自动续期
sudo certbot --nginx -d example.com
sudo certbot renew --dry-run
# 设置crontab自动续期
0 12 * * * /usr/bin/certbot renew --quiet
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' cdn.example.com";
add_header Referrer-Policy "no-referrer-when-downgrade";
# 隐藏Server头
server_tokens off;
# 禁用目录列表
autoindex off;
# 保护敏感文件
location ~* /(\.git|\.env|config\.php) {
deny all;
return 404;
}
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$http_x_forwarded_for';
access_log /var/log/nginx/security.log security;
error_log /var/log/nginx/error.log warn;
#!/bin/bash
# 监控异常请求
tail -f /var/log/nginx/security.log | grep -E '40[0-9]|50[0-9]'
# 并发连接监控
watch -n 5 "netstat -an | grep :443 | wc -l"
# 加载ModSecurity模块
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
# 配合fail2ban使用
location ~* /wp-login.php {
include /etc/nginx/fail2ban/wp-login.conf;
}
# 验证合法User-Agent
if ($http_user_agent ~* (wget|curl|nikto|sqlmap)) {
return 403;
}
# 验证合法Referer
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
# 临时封锁IP
iptables -A INPUT -s 192.168.1.100 -j DROP
# 查找攻击源并封锁
grep 'POST /wp-login.php' /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr
# 快速启用维护模式
server {
listen 80;
server_name example.com;
return 503;
}
error_page 503 @maintenance;
location @maintenance {
root /var/www/maintenance;
rewrite ^(.*)$ /maintenance.html break;
}
通过以上策略的综合实施,可以显著提升Nginx服务器的安全性,有效防御常见Web攻击。建议定期进行安全审计和渗透测试,确保持续的安全防护效果。