$ssl_alpn_protocol

变量 $ssl_alpn_protocol 包含在 TLS 握手期间选择的应用层协议协商 (ALPN) 协议。 — NGINX Core (HTTP)

$ssl_alpn_protocol NGINX Core (HTTP)

说明

$ssl_alpn_protocol 变量特定于在 TLS 握手期间使用 ALPN 的配置,例如 HTTP/2 或其他协议。当通过 HTTPS 建立连接时会设置该变量,从而允许服务器确定客户端选择了哪个应用层协议。它主要对那些在服务中实现协议可变性的服务器有用,例如根据客户端能力同时提供基于 HTTP/1.1 和 HTTP/2 的内容。该变量的值可以是协议名称,例如表示协商协议的 'h2'(用于 HTTP/2)或 'http/1.1'。 该变量对于性能优化尤为重要,因为它允许服务器根据 ALPN 列表使用客户端支持的最合适协议来响应请求。当客户端发起 TLS 握手时,它可以提出多个协议,服务器为该会话决定最合适的协议。如果客户端不支持服务器提供的任何协议,该变量将不会被设置,并且通常会回退到默认协议,通常是 HTTP/1.1。该协商机制可增强不同客户端实现之间的兼容性和性能。

配置示例

server {
    listen 443 ssl;
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    # Using the variable in a log format to capture the negotiated protocol
    access_log /var/log/nginx/access.log custom_format;

    location / {
        if ($ssl_alpn_protocol = 'h2') {
            # Perform actions specific to HTTP/2
        }
        # Other processing...
    }
}

log_format custom_format '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" Protocol: $ssl_alpn_protocol';

子系统

http

可缓存

上下文

http, server, location, if

确保您的服务器已配置为处理支持 ALPN 的协议。如果配置不正确,$ssl_alpn_protocol 可能返回空值。

仅在启用 SSL/TLS 时使用该变量,因为在非-TLS 连接中它不会被设置。

在与重定向规则结合使用时请谨慎,因为某些配置可能会无意中更改接收到的协议。