HTTP/2服务端推送(Server Push)是HTTP/2的一个重要特性,允许服务器主动向客户端推送资源,而不需要客户端明确请求。以下是配置Nginx支持HTTP/2服务端推送的完整指南:
nginx -v
如果版本低于1.13.9,需要升级。
对于Ubuntu/Debian:
sudo apt update
sudo apt install --only-upgrade nginx
对于CentOS/RHEL:
sudo yum update nginx
或者从源码编译安装最新版:
wget http://nginx.org/download/nginx-1.25.3.tar.gz
tar -xzvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
./configure --with-http_ssl_module --with-http_v2_module
make
sudo make install
编辑Nginx配置文件(通常在/etc/nginx/nginx.conf
或/etc/nginx/sites-available/your-site
):
server {
listen 443 ssl http2; # 启用HTTP/2
ssl_certificate /path/to/your/cert.pem;
ssl_certificate_key /path/to/your/privkey.pem;
# 其他SSL配置...
location / {
root /var/www/html;
index index.html;
# 启用HTTP/2服务端推送
http2_push /style.css; # 推送CSS文件
http2_push /script.js; # 推送JS文件
http2_push /image.jpg; # 推送图片
}
}
sudo nginx -t # 测试配置
sudo systemctl restart nginx # 重启Nginx
在HTML中使用Link
头部预加载资源:
<link rel="preload" href="/style.css" as="style">
<link rel="preload" href="/script.js" as="script">
然后在Nginx中:
location = /index.html {
add_header Link "</style.css>; rel=preload; as=style";
add_header Link "</script.js>; rel=preload; as=script";
}
使用Nginx的ngx_http_headers_module
模块动态设置推送资源:
location / {
# 动态设置推送
add_header Link "</style.css>; rel=preload; as=style";
add_header Link "</script.js>; rel=preload; as=script";
}
使用Chrome开发者工具:
使用命令行工具:
nghttp -ans https://yourdomain.com
如果推送不工作:
1. 确认Nginx版本支持HTTP/2推送
2. 检查SSL配置是否正确
3. 确保客户端支持HTTP/2(现代浏览器都支持)
4. 检查Nginx错误日志:sudo tail -f /var/log/nginx/error.log
通过以上步骤,您的Nginx服务器应该能够成功支持HTTP/2服务端推送功能。