http2完全兼容http1.1。http2的优点请参考:https://zhuanlan.zhihu.com/p/26559480。
这里以nginx为例:
条件:
1. 软件:
nginx -V查版本,需大于1.9.5,并且已经开启“ with-http_v2_module ”
openssl version查版本,需大于1.0.2k
2. 需要开启https:
listen 443 ssl;
改成
listen 443 ssl http2;
然后重启nginx即可。
全部nginx的server配置如下:
server {
listen 80;
listen 443 ssl http2; # 支持http2
server_name m.xxx.com;
index index.php index.html index.htm;
root /home/wwwroot/default/m.xxx.com;
if ($scheme = http ) {
return 301 https://$host$request_uri;
}
if ($server_port = 80 ) {
return 301 https://$host$request_uri;
}
#ssl on; //这行必须要注释掉
ssl_certificate /usr/local/nginx/conf/https/m.xxx.com_chain.crt;
ssl_certificate_key /usr/local/nginx/conf/https/m.xxx.com_key.key;
# 其他
#astcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#error_page 404 /404.html;
# Deny access to PHP files in specific directory
#location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; }
location / {
try_files $uri $uri/ /index.php?$query_string;
}
include enable-php.conf;
location /nginx_status
{
stub_status on;
access_log off;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 12h;
}
location ~ /.well-known {
allow all;
}
location ~ /\.
{
deny all;
}
#access_log /home/wwwlogs/access.log;
}
3. 查看网站或接口是否已经支持http2
方法1:浏览器安装一个插件:HTTP Indicator ,下载:https://chrome.google.com/webstore/detail/http-indicator/hgcomhbcacfkpffiphlmnlhpppcjgmbl
显示为彩色则表示已开启:
方法2:使用js:
(function(){
// 保证这个方法只在支持loadTimes的chrome浏览器下执行
if(window.chrome && typeof chrome.loadTimes === 'function') {
var loadTimes = window.chrome.loadTimes();
var spdy = loadTimes.wasFetchedViaSpdy;
var info = loadTimes.npnNegotiatedProtocol || loadTimes.connectionInfo;
// 就以 「h2」作为判断标识
if(spdy && /^h2/i.test(info)) {
return console.info('本站点使用了HTTP/2');
}
}
console.warn('本站点没有使用HTTP/2');
})();
结果:
-