歡迎關(guān)注我的個(gè)人博客 https://gaoyuexiang.cn
這個(gè)五一折騰了下https,看了加密的建立過程和原理,然后動(dòng)手實(shí)踐,把博客從不支持https的阿里云虛機(jī)上搬到了新買的騰訊云的主機(jī)上,配好了https,這里記錄一下。
加密連接建立過程與原理
這個(gè)部分不想自己寫了,參見 sf 上的這篇文章就很容易理解。
我的理解
https并不是一個(gè)全新的協(xié)議,而是一個(gè)組合的協(xié)議,是ssl與http組合而來的,其模型如下圖

不難發(fā)現(xiàn)其實(shí)https就是在ssl連接的基礎(chǔ)上對http報(bào)文進(jìn)行加密后發(fā)送。通過抓包,我們不難發(fā)現(xiàn)這一點(diǎn):
以
segmentfault.com為例,用wireshark抓取發(fā)送的數(shù)據(jù)包
用
http關(guān)鍵字進(jìn)行篩選:
alt text
用
ip.addr關(guān)鍵字進(jìn)行篩選
alt text
從截圖可以看出:
數(shù)據(jù)包的抓取并不能獲取到
http協(xié)議的任何信息,哪怕是URL也不行通過
ip地址獲取到的數(shù)據(jù)包,應(yīng)用層協(xié)議是SSL,在協(xié)議的報(bào)文中包含加密數(shù)據(jù)包的協(xié)議,加密協(xié)議的版本等信息,但無法獲取原始報(bào)文
按照這個(gè)邏輯,我們就可以對所有應(yīng)用層的協(xié)議進(jìn)行加密工作,比如sftp。另外,最讓碼農(nóng)感覺幸福的是,只要服務(wù)器做好配置,我們不需要修改代碼,只需要修改接口的協(xié)議,其加密過程對于程序來說是透明的。
letsencrypt
Let's Encrypt 是一個(gè)提供免費(fèi)SSL證書的項(xiàng)目,托管在github上:
https://github.com/letsencrypt/letsencrypt
有了這個(gè)項(xiàng)目,我們可以方便的把自己的站點(diǎn)升級成為https
然而,這個(gè)項(xiàng)目提供的證書默認(rèn)有效期是 90 天,我們需要定期的更新證書,或者寫個(gè)腳本,定時(shí)執(zhí)行。
實(shí)戰(zhàn)
準(zhǔn)備工作
在獲取證書的時(shí)候,需要使用 80 和 443 端口,所以需要先關(guān)閉占用這兩個(gè)端口的程序
# systemctl stop nginx.service
獲取letsencrypt
# git clone https://github.com/letsencrypt/letsencrypt
# cd letsencrypt
# ./letsencrypt-auto -h
最后一個(gè)命令會(huì)幫助解決項(xiàng)目的依賴問題
獲取證書
上一個(gè)命令結(jié)束后會(huì)打印出一些使用的幫助信息,可以根據(jù)幫助信息選擇需要的參數(shù)。
因?yàn)槲业恼军c(diǎn)部署在nginx上,所以使用如下命令:
# ./letsencrypt-auto certonly --standalone --email melo@gaoyuexiang.cn -d gaoyuexiang.cn -d www.gaoyuexiang.cn
如果得到如下信息則說明證書已經(jīng)正確獲得了:
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at
/etc/letsencrypt/live/gaoyuexiang.cn/fullchain.pem. Your cert will
expire on 2016-08-01. To obtain a new version of the certificate in
the future, simply run Let's Encrypt again.
- If you like Let's Encrypt, please consider supporting our work by:
Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le
配置nginx
nginx的配置能夠在網(wǎng)上找到很多資料,這里我就把我的與ssl相關(guān)的配置貼出來
#https配置
server{
listen 443 ssl;
root /opt/wordpress;
ssl_certificate /etc/letsencrypt/live/gaoyuexiang.cn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/gaoyuexiang.cn/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL;
...
}
#強(qiáng)制使用https
server {
listen 80;
server_name gaoyuexiang.cn;
#強(qiáng)制將 http 訪問轉(zhuǎn)發(fā)到 https
rewrite ^/(.*) https://$server_name$1 permanent;
}
配置完成,啟動(dòng)nginx和php-fpm
# systemctl start nginx.service
# systemctl start php-fpm.service
然后訪問自己的站點(diǎn),發(fā)現(xiàn)已經(jīng)能夠強(qiáng)制使用https了。
wordpress還有一些設(shè)置需要調(diào)整,把以前使用http鏈接本站資源的地方給改過來,如站點(diǎn)URL、主題使用的圖片等信息

