插件窝 干货文章 Nginx的IPv6网络安全实践

Nginx的IPv6网络安全实践

Nginx limit IPv6 ipv 270    来源:    2025-04-20

Nginx IPv6网络安全实践指南

1. IPv6基础配置

启用IPv6监听

server {
    listen [::]:80 ipv6only=off;  # 同时监听IPv4和IPv6
    listen [::]:443 ssl ipv6only=off;

    # 或者单独监听IPv6
    # listen [::]:80;
    # listen [::]:443 ssl;
}

获取真实客户端IP

set_real_ip_from ::/0;
real_ip_header X-Forwarded-For;

2. 访问控制

IPv6地址范围限制

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;
    }
}

3. 安全加固

限制连接速率

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;
}

禁用危险HTTP方法

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

4. SSL/TLS配置

仅支持安全协议和加密套件

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';
ssl_prefer_server_ciphers on;

启用HSTS

add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";

5. 日志记录

增强日志格式

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;

6. 防范DDoS攻击

限制连接数和请求速率

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;
}

启用SYN Cookies保护

# 在系统层面启用
sysctl -w net.ipv6.tcp_syncookies=1

7. IPv6防火墙规则示例

# 允许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

8. 定期检查

建议定期: 1. 检查Nginx日志中的可疑IPv6地址 2. 更新GeoIP数据库 3. 审查SSL证书和配置 4. 测试IPv6连接性和安全性

通过以上实践,可以显著提高Nginx在IPv6环境下的安全性,防范常见的网络攻击。