Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Bash 腳本實戰(十九):Nginx 一鍵編譯、HTTPS 證書生成與服務註冊

自動化部署要完成的五件事:

  1. 編譯
  2. 安裝
  3. 產生 HTTPS 證書
  4. 部署設定
  5. 註冊為 Ubuntu 服務

先把 Nginx 原始碼壓縮檔解壓並放到專案目錄,要用的設定檔放進 conf,另外準備作為 service 用的啟動腳本 nginx。目錄結構如下:

# tree -L 2
.
├── conf
│   ├── agol.conf
│   └── nginx.conf
├── install.sh
├── install.sh~
├── nginx
└── nginx-1.2.3
    ├── auto
    ├── CHANGES
    ├── CHANGES.ru
    ├── conf
    ├── configure
    ├── contrib
    ├── html
    ├── LICENSE
    ├── man
    ├── README
    └── src

8 directories, 10 files

install.sh

#!/bin/bash

source ../common/tool.sh

installDpkg "libpcre3"
installDpkg "libpcre3-dev"
installDpkg "libssl-dev"
installDpkg "openssl"

cd ./nginx-1.2.3
./configure --prefix=/usr/nginx --with-http_ssl_module
make
make install

cd ../

cp ./nginx /etc/init.d/
update-rc.d nginx defaults

cp -r ./conf/* /usr/nginx/conf/

#generate ssl certificate-begin
cd /usr/nginx/conf
openssl genrsa -des3 -out server.key -passout pass:freebird 1024
openssl req -new -key server.key -out server.csr -passin pass:freebird -batch
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key -passin pass:freebird
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

cd -
#generate ssl certificate-end

service nginx start

cd ./nginx-1.2.3
make clean

證書生成為何要用批次模式

互動式的 openssl 會停下來問一堆問題(國家、省份、組織名稱……)還要輸入兩次口令,腳本跑到一半就卡住。批次寫法把這些都消滅:

  • openssl genrsa 加上 -passout pass:freebird,避免提示輸入口令。
  • openssl req 加上 -passin pass:freebird -batch,一次提供口令並跳過所有問答。
  • openssl rsa 同樣用 -passin 提供口令,把加密的私鑰轉成無口令版本,Nginx 重啟時才不會卡在輸入 passphrase。

要提醒的是,這裡把口令硬寫在腳本裡、且產出的 server.key 已去保護,只適合測試環境;正式環境應該改用受保護的私鑰搭配 ssl_password_file,或把口令放進權限受限的外部檔案。最後 make clean 清掉編譯產物,讓專案目錄保持乾淨。

Nginx 啟動腳本可參考另一篇:https://www.linuxidc.com/Linux/2011-09/42144.htm

Copyright © Linux教程網 All Rights Reserved