Nginx的安全策略配置主要包括以下几个方面:
限制连接数:
http {
...
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
...
server {
...
location / {
limit_req zone=mylimit burst=5;
...
}
}
}
防止DDoS攻击:
使用ngx_http_limit_conn_module
和ngx_http_limit_req_module
模块来限制每个IP的连接数和请求速率。
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/fullchain.pem;
ssl_certificate_key /path/to/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
}
基于IP的访问控制:
location /admin {
allow 192.168.1.1;
deny all;
}
基于用户的认证:
使用auth_basic
和auth_basic_user_file
指令进行基本认证。
location /protected {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
配置安全头:
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
限制敏感文件的访问:
location ~ /\.ht {
deny all;
}
http {
...
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main buffer=32k flush=300s;
error_log /var/log/nginx/error.log warn;
...
}
sudo iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m limit --limit 50/q --limit-burst 50 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -m state --state NEW -m limit --limit 50/q --limit-burst 50 -j ACCEPT
ngx_http_security_headers_module
来增强安全性。通过上述措施,可以显著提高Nginx服务器的安全性。请根据具体需求和环境调整配置。