快速搭建本地HTTP/2服务

背景

2015年5月 HTTP/2 标准协议正式发布后,已得到绝大部分的浏览器的支持,但截止发文时使用的网站占比还不到1/3
本文目的是为了快速搭建一个本地HTTP/2服务,以供研发小伙伴开发测试,从而加深对HTTP/2的理解。

环境

  1. OpenSSL: 1.0.2q
  2. Nginx: 1.15.7

步骤

  1. 生成本地根证书:
1
2
3
4
5
# 使用AES256-bit编码加密生成4096位的根秘钥
openssl genrsa -aes256 -out rootCA.key 4096

Enter pass phrase for rootCA.key: password
Verifying - Enter pass phrase for rootCA.key: password

各参数可以查看man ca 或者 查阅这里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 使用根秘钥生成根证书
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem

Enter pass phrase for rootCA.key: password
You are about to be asked to enter information that will be incorporated
...
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:Beijing
Locality Name (eg, city) []:Beijing
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Lovecoding.org
Organizational Unit Name (eg, section) []:Lovecoding CA
Common Name (e.g. server FQDN or YOUR name) []:Lovecoding ROOT CA
Email Address []:
Generating a RSA private key
  1. 生成本地自签证书
1
2
3
4
5
#生成自签秘钥
openssl req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config server.csr.cnf

#生成自签证书
openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 600 -sha256 -extfile v3.ext

其中server.csr.cnf:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = req_distinguished_name

[ req_distinguished_name ]
C = CN
ST = Beijing
L = Beijing
O = MyOrganization
OU = MyOrganizationUnit
emailAddress = lovecoding@example.com
CN = localhost

v3.ext:

1
2
3
4
5
6
7
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName=@alt_names

[alt_names]
DNS.1=localhost
  1. 配置nginx

server.crtserver.key添加到nginx:

1
2
3
4
5
6
7
8
9
10
11
server {
listen [::]:443 ssl http2 ipv6only=on;
listen 443 ssl http2;
ssl_certificate /etc/nginx/certs/server.crt;
ssl_certificate_key /etc/nginx/certs/server.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_session_cache shared:SSL:1m;

server_name localhost;
...

重启nginx:

1
2
sudo nginx -t
sudo nginx -s reload

  1. 信任自签证书

首次打开网页时,会提示证书无效,那么将自签的证书加入信任列表即可:

  • Mac OS
1
sudo security add-trusted-cert -d -r trustAsRoot -k /Library/Keychains/System.keychain server.crt
  • Ubuntu:
1
2
sudo cp server.crt /usr/local/share/ca-certificates/server.crt
sudo update-ca-certificates

其他系统可以查阅这里

此时打开浏览器可以看到:



说明自签证书已有效,并支持HTTP/2服务。

总结

本文介绍了本地快速搭建HTTP/2服务,希望对研发伙伴有所帮助。目前所有代码都已放到local-http2,喜欢的同学可以Star :)。
还有HTTP/3草案已出,感兴趣的可以了解一下。

参考