nginx-Let's Encrypt
在Ubuntu系統(tǒng)上為nginx反向代理站點配置Let's Encrypt陨溅,實現(xiàn)SSL即https訪問:
安裝Let's Encrypt客戶端
下載Let's Encrypt客戶端certbot-auto
到/usr/local/sbin
目錄:
$ cd /usr/local/sbin
$ sudo wget https://dl.eff.org/certbot-auto
使該腳本可執(zhí)行:
$ sudo chmod a+x /usr/local/sbin/certbot-auto
這樣一來遇骑,certbot-auto
應(yīng)該已經(jīng)可以使用了艘绍。
獲取Let's Encrypt證書
修改nginx配置文件中server
區(qū)塊,使子目錄.well-known
指向本地:
server {
listen 80;
server_name sub.domain.com www.sub.domain.com;
[…]
location /.well-known {
alias /var/www/sub.domain.com/.well-known;
}
location / {
# proxy commands go here
[…]
}
}
Let's Encrypt服務(wù)器為嘗試訪問http://sub.domain.com/.well-known
來驗證服務(wù)器病毡。
然后就可以使用certbot-auto客戶端來獲取證書了先匪,獲取證書時需要輸入你的Email并接受用戶條款:
certbot certonly --webroot -w /var/www/sub.domain.com/ -d sub.domain.com -d www.sub.domain.com
Enter an email address
如果成功獲取證書捎拯,屏幕上會顯示證書存放位置和過期時間。你的密鑰和證書存放在
/etc/letsencrypt/live/sub.domain.com/
目錄毯欣。
配置nginx啟用證書
在配置文件上新建一個server
語塊:
server {
listen 443 ssl;
# if you wish, you can use the below line for listen instead
# which enables HTTP/2
# requires nginx version >= 1.9.5
# listen 443 ssl http2;
server_name sub.domain.com www.sub.domain.com;
ssl_certificate /etc/letsencrypt/live/sub.domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/sub.domain.com/privkey.pem;
# Turn on OCSP stapling as recommended at
# https://community.letsencrypt.org/t/integration-guide/13123
# requires nginx version >= 1.3.7
ssl_stapling on;
ssl_stapling_verify on;
# Uncomment this line only after testing in browsers,
# as it commits you to continuing to serve your site over HTTPS
# in future
# add_header Strict-Transport-Security "max-age=31536000";
access_log /var/log/nginx/sub.log combined;
# maintain the .well-known directory alias for renewals
location /.well-known {
alias /var/www/sub.domain.com/.well-known;
}
location / {
# proxy commands go here as in your port 80 configuration
[…]
}
}
重新載入nginx:
service nginx reload
現(xiàn)在馒过,在瀏覽器中訪問https://sub.domain.com
和https://www.sub.domain.com
,測試一下HTTPS是否正常酗钞、瀏覽器有沒有報證書錯誤腹忽。
HTTP重定向至HTTPS
把nginx配置文件中80端口的server
語塊改為如下:
server {
listen 80;
server_name sub.domain.com www.sub.domain.com;
rewrite ^ https://$host$request_uri? permanent;
}
在443端口的配置中来累,反注釋下面語句,使其啟用HSTS(HTTP嚴格傳輸安全):
add_header Strict-Transport-Security "max-age=31536000";
重新載入nginx即可窘奏。
自動更新證書
你可以使用以下語句來更新所有超過60天的證書:
certbot-auto renew --renew-hook "service nginx reload"
也可以把更新命令寫入/etc/crontab
嘹锁,實現(xiàn)自動更新:
# at 4:47am/pm, renew all Let's Encrypt certificates over 60 days old
47 4,16 * * * root certbot-auto renew --quiet --renew-hook "service nginx reload"
測試更新操作:
certbot-auto --dry-run renew
強制提前更新證書:
certbot-auto renew --force-renew --renew-hook "service nginx reload"
你可以無數(shù)次測試更新操作,但是實際的更新證書有頻率限制着裹。
參考資料