location /admin/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
location /secure/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /api/ {
limit_except GET POST {
deny all;
}
}
防护措施:
location ~* \.(php|asp|jsp)$ {
deny all;
}
location / {
autoindex off;
}
防护措施:
server {
# 确保每个请求只解析一个请求头
http2_max_requests 1;
# 禁用分块传输编码
chunked_transfer_encoding off;
}
防护措施:
server {
# 严格检查请求头
underscores_in_headers off;
# 禁用非标准请求头
ignore_invalid_headers on;
}
防护措施:
server {
# 设置连接超时
client_body_timeout 10s;
client_header_timeout 10s;
# 限制请求体大小
client_max_body_size 1m;
# 限制请求速率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
}
add_header X-XSS-Protection "1; mode=block";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
server {
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 10m;
ssl_stapling on;
ssl_stapling_verify on;
}
server_tokens off;
more_clear_headers Server;
location ~ /\.(ht|git|svn) {
deny all;
}
location ~* \.(ini|conf|env|log)$ {
deny all;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
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;
map $request_uri $is_suspicious {
default 0;
~*\.php 1;
~*\.asp 1;
~*\.jsp 1;
~*\.exe 1;
~*\.sh 1;
}
server {
if ($is_suspicious) {
access_log /var/log/nginx/suspicious.log security;
}
}
nginx -t
测试配置语法通过实施这些访问控制和安全措施,可以显著提高Nginx服务器的安全性,防范常见Web攻击。