1. 程式人生 > 其它 >基於Nginx網站切換HTTPS方式訪問

基於Nginx網站切換HTTPS方式訪問

Linux系統下生成證書

生成祕鑰key,執行:   填寫密碼

[arcana@huangning ~]$  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:

然後你就獲得了一個server.key檔案. 
以後使用此檔案(通過openssl提供的命令或API)可能經常回要求輸入密碼,如果想去除輸入密碼的步驟可以使用以下命令:

[arcana@huangning ~]$ openssl rsa -in server.key -out server.key
Enter pass phrase for server.key:
writing RSA key

建立伺服器證書的申請檔案server.csr,執行:

openssl req -new -key server.key -out server.csr

其中Country Name填CN,Common Name填主機名也可以不填,如果不填瀏覽器會認為不安全.(例如你以後的url為https://abcd/xxxx….這裡就可以填abcd),其他的都可以不填. 
建立CA證書:

[arcana@huangning ~]$ openssl req -new -key server.key -out server.csr
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) [XX]:CN State or Province Name (full name) []:Shanghai Locality Name (eg, city) [Default City]:Shanghai Organization Name (eg, company) [Default Company Ltd]:dm Organizational Unit Name (eg, section) []:dm Common Name (eg, your name or your server's hostname) []:dilogger Email Address []:tonyandrewhn@126.com Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:psc@2021 An optional company name []:dm [arcana@huangning ~]$

此時,你可以得到一個ca.crt的證書,這個證書用來給自己的證書籤名. 


建立自當前日期起有效期為期十年的伺服器證書server.crt:

[arcana@huangning ~]$ openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey server.key -CAcreateserial -out server.crt
Signature ok
subject=/C=CN/ST=Shanghai/L=Shanghai/O=dm/OU=dm/CN=dilogger/emailAddress=tonyandrewhn@126.com
Getting CA Private Key

ls你的資料夾,可以看到一共生成了5個檔案:

ca.crt   ca.srl    server.crt   server.csr   server.key

其中,server.crt和server.key就是你的nginx需要的證書檔案. 

 

如何配置nginx

開啟你的nginx配置檔案,修改nginx.conf找到https的配置,去掉這段程式碼的註釋.或者直接複製我下面的這段配置:

    server {
        listen       8443 default_server;
        server_name  _;
        ssl on;
        ssl_certificate /home/arcana/server.crt;#配置證書位置
        ssl_certificate_key /home/arcana/server.key;#配置祕鑰位置  
        #ssl_client_certificate ca.crt;#雙向認證
        ##ssl_verify_client on; #雙向認證
        #ssl_session_timeout 5m;
        #ssl_protocols SSLv2 SSLv3 TLSv1;
        #ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        #ssl_prefer_server_ciphers on;

 nginx -s reload 

訪問介面示意圖:

 

 

It‘s work.