必要條件
產生憑證需要 OpenSSL 類別庫,請先確認系統是否已安裝 OpenSSL。
若尚未安裝,可透過以下方式安裝:
Mac OS X 使用 Homebrew 安裝
$ brew install openssl
Windows 可到此網站下載安裝檔:OpenSSL for Windows
Ubuntu/Debian Linux
$ sudo apt-get install openssl
RedHat/CentOS Linux
$ sudo yum install openssl
步驟一:建立存放憑證的資料夾
$ mkdir /etc/nginx/ssl $ cd /etc/nginx/ssl
步驟二:建立伺服器私鑰及憑證
建立伺服器私鑰
開始建立伺服器私鑰。過程中,將會提示輸入密碼,請牢記此密碼,若忘記或遺失該密碼,將無法存取憑證。
$ sudo openssl genrsa -des3 -out server.key 2048
以下為建立私鑰時可能會看到的訊息
Generating RSA private key, 2048 bit long modulus
....................+++
..............................................................+++
e is 65537 (0x10001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:
建立伺服器憑證
建立時會詢問私鑰密碼,若密碼不正確便無法建立憑證。
建立憑證時,最重要的欄位為 Common Name。請在此輸入網域名稱,若沒有網域名稱則輸入網站 IP。並請不要填寫 challenge password 及 optional company name 欄位。
$ sudo openssl req -new -key server.key -out server.csr
以下為建立憑證時可能會看到的訊息
Enter pass phrase for server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]: TW
State or Province Name (full name) [Some-State]: Taipei
Locality Name (eg, city) []: Taipei
Organization Name (eg, company) [Internet Widgits Pty Ltd]: Example Inc
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []: example.com
Email Address []: admin@example.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
步驟三:移除伺服器私鑰密碼(Passphrase)
雖然密碼可提供高度的安全性,但若有人重載 nginx 則會產生問題。在 nginx 崩潰或需要重新啟動時,永遠都需要輸入密碼才能使網頁伺服器上線。
$ sudo cp server.key server.key.origin
$ sudo openssl rsa -in server.key.org -out server.key
步驟四:為憑證簽章
可以自行指定該憑證有效期限,在此範例中憑證為 1 年後到期。
$ sudo openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
現在所需的憑證已產生完畢!
步驟五:設定憑證
開啟 nginx 設定檔,加入以下設定,請記得將 server_name 改為網域名稱或 IP。
# HTTPS server
server {
listen 443;
server_name example.com;
ssl on;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
}
重新啟動 nginx
$ sudo /etc/init.d/nginx restart
前往 https://domain_name 將會看到自行簽章的憑證。