server {
listen [::]:80 ipv6only=off; # 同时监听IPv4和IPv6
listen [::]:443 ssl ipv6only=off;
# 或者单独监听IPv6
# listen [::]:80;
# listen [::]:443 ssl;
}
set_real_ip_from ::/0;
real_ip_header X-Forwarded-For;
location /admin/ {
allow 2001:db8::/32; # 只允许特定IPv6前缀访问
allow 2001:db8:abcd:1234::/64;
deny all;
}
geoip6 /usr/share/GeoIP/GeoIPv6.dat;
map $geoip6_country_code $allowed_country {
default no;
CN yes; # 只允许中国IPv6地址访问
HK yes;
MO yes;
TW yes;
}
server {
if ($allowed_country = no) {
return 403;
}
}
limit_conn_zone $binary_remote_addr zone=ipv6_conn:10m;
limit_req_zone $binary_remote_addr zone=ipv6_req:10m rate=10r/s;
server {
limit_conn ipv6_conn 10;
limit_req zone=ipv6_req burst=20 nodelay;
}
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
log_format ipv6 '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$ssl_protocol $ssl_cipher';
access_log /var/log/nginx/ipv6_access.log ipv6;
limit_conn_zone $binary_remote_addr zone=ipv6_conn_limit:10m;
limit_req_zone $binary_remote_addr zone=ipv6_req_limit:10m rate=100r/s;
server {
limit_conn ipv6_conn_limit 20;
limit_req zone=ipv6_req_limit burst=50 nodelay;
}
# 在系统层面启用
sysctl -w net.ipv6.tcp_syncookies=1
# 允许HTTP/HTTPS
ip6tables -A INPUT -p tcp --dport 80 -j ACCEPT
ip6tables -A INPUT -p tcp --dport 443 -j ACCEPT
# 限制ICMPv6 (防止Ping洪水攻击)
ip6tables -A INPUT -p icmpv6 --icmpv6-type echo-request -m limit --limit 10/second -j ACCEPT
ip6tables -A INPUT -p icmpv6 --icmpv6-type echo-request -j DROP
# 防止碎片攻击
ip6tables -A INPUT -m frag -j DROP
建议定期: 1. 检查Nginx日志中的可疑IPv6地址 2. 更新GeoIP数据库 3. 审查SSL证书和配置 4. 测试IPv6连接性和安全性
通过以上实践,可以显著提高Nginx在IPv6环境下的安全性,防范常见的网络攻击。