Configure Nginx with HTTP/2 Support

刚发布不久的 Nginx 1.9.5 正式支持HTTP/2,于是就来折腾一番吧。由于 HTTP/2 是基于 https, 因此必须先配置 Nginx 支持 https。文中所有操作都在自己本地机器上进行测试,采用的是 openssl 生成自签名证书。

  1. 创建 Key:

    1
    $ openssl genrsa -des3 -out test.key 1024
  2. 创建签名请求:

    1
    $ openssl req -new -subj "/C=US/ST=Mars/L=iTranswarp/O=iTranswarp/OU=iTranswrap/CN=test" -key test.key -out test.csr

    在实际部署时,必须将 CN 字段中的 test 换成域名,否则无法通过浏览器验证。

  3. 将 Key 的口令移除:

    1
    2
    $ mv test.key test.origin.key
    $ openssl rsa -in test.origin.key -out test.key
  4. 用Key签名证书:

    1
    $ openssl x509 -req -days 3650 -in test.csr -signkey test.key -out test.crt
  5. 配置 Nginx

    • 重定向所有的流量到 SSL/TLS
    1
    2
    3
    4
    5
    6
    server {
    listen 80;
    location / {
    return 301 https://$host$request_uri;
    }
    }
    • 启用 HTTP/2
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    server {
    listen 443 ssl http2 default_server;
    server_name localhost;
    keeplive_timeout 70;

    ssl_certificate /path/to/test.crt;
    ssl_certificate_key /path/to/test.key;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
    ssl_prefer_server_ciphers on;
    }
  6. 重新加载配置文件

    1
    2
    $ sudo nginx -t   # 检验配置文件是否有错误
    $ sudo nginx -s reload

Refferences:

  1. https://www.nginx.com/blog/nginx-1-9-5/
  2. http://www.liaoxuefeng.com/article/0014189023237367e8d42829de24b6eaf893ca47df4fb5e000