Nginx:一款輕量級的Web 服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器,在一個BSD-like 協議下發行,其特點是佔有內存少,併發能力強。
Https:安全套接字層超文本傳輸協議,它在HTTP的基礎上加入了SSL/TLS協議,SSL/TLS依靠證書來驗證服務器的身份,併爲瀏覽器和服務器之間的通信加密,默認端口爲443。
SSL/TLS:爲網絡通信提供安全及數據完整性的一種安全協議,TLS與SSL在傳輸層對網絡連接進行加密,提供如下服務:
1)認證用戶和服務器,確保數據發送到正確的客戶機和服務器;
2)加密數據以防止數據中途被竊取;
3)維護數據的完整性,確保數據在傳輸過程中不被改變。
SSL證書是一種數字證書,它能夠使用 SSL/TLS協議在瀏覽器和 Web 服務器之間建立一條安全通道。
一、SSL證書
要想使用https進行通信,首先需要獲得SSL證書,有兩種方式:
1)申請證書
可以向證書頒發機構或雲服務提供商進行申請,有免費和收費兩種。
2)使用openssl生成證書
該證書生成方式如下:
1、在當前目錄生成一個名爲server(名稱自定義)的RSA私鑰文件
$ openssl genrsa -des3 -out server.key 1024
生成密鑰文件的過程中需要輸入密碼,需暫時記住該密碼,後續會用到。
2、生成一個不需要輸入密碼的密鑰文件
建議先對原密鑰文件進行備份,如
cp server.key server.key.org
然後使用備份的密鑰文件進行生成,如
openssl rsa -in server.key.org -out server.key
3、生成證書的申請文件
使用openssl命令在當前目錄下,生成一個申請文件server.csr(文件名自定義)
$ openssl req -new -key server.key -out server.csr
在生成證書申請文件過程中會提示輸入一些信息,如下:
Enter pass phrase for root.key: #輸入前面創建的密碼
Country Name (2 letter code) [AU]:CN #國家代號,中國輸入CN
State or Province Name (full name) [Some-State]:BeiJing #省的全名,拼音
Locality Name (eg, city) []:BeiJing #市的全名,拼音
Organization Name (eg, company) [Internet Widgits Pty Ltd]:MyCompany Corp. #公司英文名
Organizational Unit Name (eg, section) []: # 可以不輸入
Common Name (eg, YOUR name) []: xxx
Email Address []:[email protected] #電子郵箱,可隨意填
Please enter the following ‘extra’ attributes
to be sent with your certificate request
A challenge password []: #可以不輸入
An optional company name []: #可以不輸入
4、簽發生成證書
$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
以上即生成了一個自己簽發的證書。
二、配置Nginx
打開Nginx的配置文件nginx.conf,向其中添加https配置,如下:
server {
listen 443 default ssl; #監聽443端口
server_name your-domain-name; #域名
ssl on; #開啓ssl
ssl_certificate /etc/nginx/ssl/server.crt; #上傳或生成證書的位置
ssl_certificate_key /etc/nginx/ssl/server.key; #上傳或生成私鑰的位置
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5; #密碼加密方式
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #支持協議
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
三、啓動Nginx
/usr/sbin/nginx -s reload
此時nginx正常啓動,即可使用https訪問web站點。
四、注意事項
1、如果在啓動過程中報"ssl" parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:37錯誤,是nginx缺少http_ssl_module模塊導致的,需要在編譯安裝configure時帶上–with-http_ssl_module配置。
2、如果nginx使用docker方式進行部署,需要對443端口進行映射,如下:
1)獲取容器ip
$ docker inspect [container_name] | grep IPAddress
2)添加轉發規則
$ iptables -t nat -A DOCKER -p tcp --dport [host_port] -j DNAT --to-destination [docker_ip]:443
其中[host_port]爲要映射的主機端口。
參考:
https://www.cnblogs.com/jingxiaoniu/p/6745254.html
https://blog.csdn.net/keketrtr/article/details/78580717
https://aotu.io/notes/2016/08/16/nginx-https/index.html