配置站點使用 HTTPS,並且將 http 重定向至 https.
1. nginx 的 ssl 模塊安裝
查看 nginx 是否安裝 http_ssl_module
模塊
$ /usr/local/nginx/sbin/nginx -V
如果出現 configure arguments: --with-http_ssl_module
, 則已安裝(下面的步驟可以跳過,進入 nginx.conf
配置)。
下載 nginx 安裝包 http://nginx.org/download/nginx-1.14.1.tar.gz
# 下載安裝包到 src 目錄
$ cd /usr/local/src
$ wget http://nginx.org/download/nginx-1.14.1.tar.gz
解壓安裝包
$ tar -zxvf nginx-1.14.1.tar.gz
配置 ssl 模塊
$ cd nginx-1.14.1
$ ./configure --prefix=/usr/local/nginx --with-http_ssl_module
使用 make
命令編譯(使用make install
會重新安裝nginx),此時當前目錄會出現 objs
文件夾。
用新的 nginx 文件覆蓋當前的 nginx 文件。
$ cp ./objs/nginx /usr/local/nginx/sbin/
再次查看安裝的模塊(configure arguments: --with-http_ssl_module
說明ssl模塊已安裝)。
$ /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.14.1
...
configure arguments: --with-http_ssl_module
2. ssl 證書部署
這里使用的是阿里雲的免費證書,期限為1年,申請地址https://common-buy.aliyun.com/?spm=5176.2020520154.0.0.45d356a7FlPIts&commodityCode=cas#/buy
(如果需要更長時間的或者其他證書可能需要購買,這里提供下阿里的優惠活動購物車優惠卷(https://promotion.aliyun.com/ntms/act/shoppingcart.html?userCode=znftgj11
)~)。
- 下載申請好的 ssl 證書文件壓縮包到本地並解壓(這里是用的 pem 與 key 文件,文件名可以更改)。
- 在 nginx 目錄新建 cert 文件夾存放證書文件。
$ cd /usr/local/nginx
$ mkdir cert
將上面解壓出來的這兩個文件上傳至服務器的 cert 目錄里
這里使用 mac 終端上傳至服務器的 scp 命令
$ scp /Users/yourname/Downloads/ssl.pem root@xxx.xx.xxx.xx:/usr/local/nginx/cert/
$ scp /Users/yourname/Downloads/ssl.key root@xxx.xx.xxx.xx:/usr/local/nginx/cert/
3. nginx.conf 配置
編輯 /usr/local/nginx/conf/nginx.conf
配置文件:
配置 https server。
注釋掉之前的 http server 配置,新增 https server:
server {
# 服務器端口使用443,開啟ssl, 這里ssl就是上面安裝的ssl模塊
listen 443 ssl;
# 域名,多個以空格分開
server_name baidu.com www.baidu.com;
# ssl證書地址
ssl_certificate /usr/local/nginx/cert/ssl.pem; # pem文件的路徑
ssl_certificate_key /usr/local/nginx/cert/ssl.key; # key文件的路徑
# ssl驗證相關配置
ssl_session_timeout 5m; #緩存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全鏈接可選的加密協議
ssl_prefer_server_ciphers on; #使用服務器端的首選算法
location / {
root html;
index index.html index.htm;
}
}
將 http 重定向 https
server {
listen 80;
server_name baidu.com www.baidu.com;
return 301 https://$server_name$request_uri;
}
4. 重啟 nginx
$ /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
如果 80 端口被占用,用kill [id]來結束進程:
# 查看端口使用
$ netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address state PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 21307/nginx: master
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 3072/sshd
tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 21307/nginx: master
# 結束 80 端口進程
$ kill 21307
再次重啟 nginx :
$ /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
無信息提示就成功啦~