---
# System prepended metadata

title: '[ssl] 利用證書操作綁定配置Nginx'
tags: [ssl, 證書]

---

# [ssl] 利用證書操作綁定配置Nginx 
###### tags: `證書` `ssl`

:::success
腳本弄成 ssl.sh
:::
![](https://i.imgur.com/hZrg0R7.png)

## :triangular_flag_on_post: 問題探討

:::warning
注意事項
:::
- www會過濾掉但配置會有添加www二級域名

```shell=
#清空或建立list
echo " " > list
#多域名證書操作
#解壓縮
ssl_zip_list=$(ls *.zip)
    for zip_file in ${ssl_zip_list};do
        echo '解壓'${zip_file}'後並刪除'
        unzip -qO UTF-8 ${zip_file} && rm -f ${zip_file}
       done
    #取要用nginx證書統一成固定型式,移除不要的項目
    ssl_dir_name=$(ls | grep -v ssl.sh |grep -v list)
    for dir_name in ${ssl_dir_name}; do
           mkdir server.com
           #先判斷是否為crt，如果不是直接轉換
           if [ -f ${dir_name}/*.pem ]; then
                  echo ${dir_name} 'pem 轉換為crt'
                  mv ${dir_name}/*.pem server.com/server.crt
           fi
           if [ -f ${dir_name}/*.crt ]; then
                  mv ${dir_name}/*.crt server.com/server.crt
           fi
           mv  ${dir_name}/*.key server.com/server.key
           rm -rf ${dir_name}
           #從crt抓取名單
           openssl x509 -in server.com/server.crt -noout -text|grep "DNS"|awk -F "," '{for(i=1;i<=NF;++i) print $i}'|grep -v www |awk -F : '{print $2}' >> list
    #根據列表多域名證書操作
    for i in `cat list`
        do
           echo $i'已完成'
           mkdir $i
           cp  server.com/server.crt $i/server.crt
           cp  server.com/server.key $i/server.key
           # 複製設定檔案 取代證書位置
           cp /opt/lucky/nginx/conf/vhosts/kc183.conf /opt/lucky/nginx/conf/vhosts/$i.conf
           sed -i "s/kc183.abcty8.com/$i www.$i/g" /opt/lucky/nginx/conf/vhosts/$i.conf
           sed -i "s/keys\/abcty\//keys\/$i\//g" /opt/lucky/nginx/conf/vhosts/$i.conf
           sed -i "s/#    if ( \$scheme \= http ){/    if ( \$scheme \= http ){/g" /opt/lucky/nginx/conf/vhosts/$i.conf
           sed -i "s/#               return 301 https:\/\/\$server_name\$request_uri;/               return 301 https:\/\/\$host\$request_uri;/g" /opt/lucky/nginx/conf/vhosts/$i.conf
           sed -i "s/#               return 301 https:\/\/\$host\$request_uri;/               return 301 https:\/\/\$host\$request_uri;/g" /opt/lucky/nginx/conf/vhosts/$i.conf
           sed -i "s/#    }/    }/g" /opt/lucky/nginx/conf/vhosts/$i.conf
           #移動到指定路徑
           mv $i /opt/lucky/nginx/conf/keys/
        done
        rm -rf server.com
        cat /dev/null > list
    done
```

:::warning
成功生產證書示意圖
:::
![](https://i.imgur.com/4g990WS.png)
![](https://i.imgur.com/TYwGxJV.png)
![](https://i.imgur.com/3E6NhUV.png)
![](https://i.imgur.com/y5PfZIr.png)

