作为IT工程师,在配置Nginx反向代理时,实施有效的防篡改策略至关重要。以下是全面的防篡改解决方案:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
}
location / {
proxy_pass http://backend;
# 验证必要请求头
if ($http_user_agent ~* "(wget|curl|libwww-perl)") {
return 403;
}
# 移除敏感头信息
proxy_hide_header X-Powered-By;
proxy_hide_header Server;
# 设置安全头
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
}
# 限制请求体大小防止缓冲区溢出攻击
client_max_body_size 10m;
client_body_buffer_size 128k;
# 验证Content-Type
location /api/ {
if ($content_type !~ "application/json") {
return 415;
}
proxy_pass http://backend_api;
}
location /secure/ {
# 验证签名参数
set $secret_key "your_shared_secret";
set $expected_signature "";
# 计算预期签名 (示例)
set_hmac_sha1 $expected_signature $secret_key "$request_uri$remote_addr$http_user_agent";
if ($arg_signature != $expected_signature) {
return 403;
}
proxy_pass http://secure_backend;
}
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://api_backend;
}
geo $blocked {
default 0;
10.0.0.0/8 1;
192.168.1.100 1;
}
server {
location / {
if ($blocked) {
return 403;
}
proxy_pass http://backend;
}
}
location / {
proxy_pass http://backend;
# 验证响应内容类型
proxy_set_header Accept "application/json";
# 响应内容长度限制
proxy_buffer_size 4k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 24k;
}
location / {
# 与ModSecurity等WAF集成
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
proxy_pass http://backend;
}
# 记录详细访问日志
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$upstream_addr $http_x_forwarded_for';
access_log /var/log/nginx/security.log security;
通过实施这些策略,可以显著提高Nginx反向代理的安全性,有效防止请求和响应被篡改。