#!/usr/bin/env bash
# 文件名: tls13-conf-with-nginx.sh
# 功能: 快速生成支持 TLS1.3 虚拟主机配置

## 更新记录

# 2019-02-27 创建脚本
# 2019-03-08 添加 "ssl_early_data"配置命令，nginx为了安全没有启用 0-RTT功能，为实现0-RTT添加


export HOST=${1:-demo.vqiu.cn}      # 访问域名
export BACKEND=${2:-1.1.1.1:80}     # 多个后端使用逗号进行隔离

cat >$PWD/${HOST}.conf<<EOF
upstream $(echo $HOST|tr '.' '_') {
    keepalive 64;

    $(for backend in $(echo $BACKEND | tr -s "," " "); do
	    echo -en "server ${backend} max_fails=3 fail_timeout=30s weight=5;\n    "; done)
}

#server {
#    listen 80;
#    server_name $HOST;
#    
#    return 302 https://$HOST\$request_uri;
#
#    error_log /dev/null;
#    access_log /dev/null;
#}

server {
    listen 443 ssl http2;
    server_name $HOST;

    ssl_certificate /etc/nginx/certs/$HOST.pem;
    ssl_certificate_key /etc/nginx/certs/$HOST.key;

    # curl https://ssl-config.mozilla.org/ffdhe2048.txt >/etc/nginx/certs/dhparam.pem
    ssl_dhparam /etc/nginx/certs/dhparam.pem;

    ssl_session_timeout       1d;
    ssl_session_cache         shared:$(echo $HOST|tr '.' '_'):10m;
    ssl_session_tickets       off;
    ssl_early_data            on;

    ssl_protocols             TLSv1.2 TLSv1.3;
    ssl_ciphers               TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:TLS13-AES-128-GCM-SHA256:EECDH+CHACHA20:EECDH+AESGCM:EECDH+AES;
    ssl_prefer_server_ciphers on;

    add_header                Strict-Transport-Security max-age=15768000; # 6 months
    
    location / {
        proxy_pass            http://$(echo $HOST|tr '.' '_');
        proxy_http_version    1.1;
        proxy_set_header      Upgrade \$http_upgrade;
        proxy_set_header      Connection "upgrade";
        proxy_set_header      Host \$http_host;
        proxy_set_header      X-Real-IP \$remote_addr;
        proxy_set_header      X-Forward-For \$proxy_add_x_forwarded_for;
        proxy_set_header      X-Forward-Proto http;
        proxy_redirect        off;
    }
    error_log  /var/log/nginx/${HOST}_error.log;
    access_log /var/log/nginx/${HOST}_access.log;
}
EOF
