Skip to content

Nginx 启用 QUIC/HTTP3

1. 确保 Nginx 版本支持

  • 需要 Nginx 1.25.0 或更高版本
  • 编译时需要启用 --with-http_v3_module 模块

2. 安装依赖

bash
sudo apt install libssl-dev

3. Nginx 配置示例

nginx
# 在 http 块中添加
http {
    # 启用 QUIC 和 HTTP/3
    quic_bpf on;
    ssl_early_data on;
    
    server {
        listen 443 quic reuseport; # QUIC 监听
        listen 443 ssl;            # 同时支持 TLS
        server_name example.com;
        
        # SSL 配置
        ssl_protocols TLSv1.3;     # QUIC 要求 TLS 1.3
        ssl_certificate /path/to/cert.pem;
        ssl_certificate_key /path/to/key.pem;
        
        # QUIC 和 HTTP/3 特定配置
        add_header Alt-Svc 'h3=":443"; ma=86400';
        
        # ...其他配置...
    }
}

4. 系统配置

可选地调整一些系统参数以优化 QUIC 性能,编辑 /etc/sysctl.conf

bash
# UDP 缓冲区配置
net.core.rmem_max = 2500000
net.core.wmem_default = 1024000
net.core.rmem_default = 1024000
net.core.wmem_max = 2500000

# UDP 连接优化
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 2000

# 启用 BBR 拥塞控制算法
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

# UDP 相关优化
net.ipv4.udp_mem = 8388608 12582912 16777216

应用配置:

bash
sudo sysctl -p

修改文件描述符限制,编辑 /etc/security/limits.conf

bash
* soft nofile 1048576
* hard nofile 1048576

修改 Nginx 文件描述符限制:

bash
nginx soft nofile 1048576
nginx hard nofile 1048576

5. 防火墙配置

确保 UDP/443 端口开放:

bash
sudo ufw allow 443/udp

使用 iptables

bash
sudo iptables -A INPUT -p udp --dport 443 -j ACCEPT

6. 检查配置

bash
nginx -t
systemctl restart nginx

验证 Nginx 是否正常启动:

bash
systemctl status nginx

验证系统配置是否生效:

bash
# 检查当前系统参数
sysctl -a | grep net.core.rmem
sysctl -a | grep net.core.wmem

# 检查 QUIC 端口是否开放
netstat -lunp | grep :443

验证 QUIC 是否生效可以使用 curl 测试:

bash
curl --http3 https://example.com

注意事项:

  • 确保服务器有有效的 SSL 证书
  • QUIC 需要 UDP 443 端口,确保防火墙和网络设备允许此流量
  • 建议使用 CDN 时也要确保 CDN 提供商支持 QUIC/HTTP3
  • 客户端浏览器需要支持 HTTP/3
  • 监控 UDP 性能和连接状态