Let’s Encrypt 获取免费TLS/SSL证书
Let’s Encrypt 获取免费TLS/SSL证书
使用Let’s Encrypt申请TLS/SSL证书,官方推荐使用certbot这套自动化工具来实现。certbot主要可以分为Standanlone和Webroot两种认证方式。Standanlone需要暂时占用服务器的80或者443端口,来进行获取和更新证书的操作。换言之,如果服务器搭建运行了网站,又不希望因为获取和更新证书导致网站暂时停止服务,那么这种方式并不理想,Webroot这种更适合。
使用Webroot认证方式
由于自己服务器本身有网站在运行,所以选择了Webroot这种方式。下面我们用Webroot的认证方式来给网站添加HTTPS,步骤如下:
安装certbot,以debian为例
1
sudo apt-get install certbot
生成证书
1
2
3
4
5sudo certbot certonly --webroot --agree-tos --email your@email.com -w 网站根目录路径 -d www.domainname.com -d domainname.com
片刻,看到下面内容就是证书生成成功了, 生成完成的证书文件会保存在固定的/etc/letsencrypt/路径下
IMPORTANT NOTES:
Congratulations! Your certificate and chain have been saved at /etc/letsencrypt/live/example.com/fullchain.pem.在node中,让网站支持HTTPS很简单
1
2
3
4
5
6
7
8
9
10
11
12
13let express = require('express');
const app = express();
// ...
let https = require('https');
let fs = require('fs');
const path = require('path');
const certDirPath = '/etc/letsencrypt/live/domainname.com'; // 路径根据你的网站目录自己设置成相对路径,domainname.com为你的域名
let options = {
keys: fs.readFileSysc(path.join(certDirPath, 'privkey.pem')),
cert: fs.readFileSysc(path.join(certDirPath, 'cert.pem'))};
https.createServer(options, app).listen(443);如果您是用nginx部署服务,那么请在etc/nginx/site-enabled目录拷贝一份默认的default,然后把default中server内容全注释掉,修改拷贝后的文件,最终配置如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62# Default server configuration
#
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name www.domainname.com;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
# pass PHP scripts to FastCGI server
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
# fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
# 重定向到HTTPS
return 301 https://$server_name$request_uri;
}
#HTTPS
#
server {
# SSL configuration
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
ssl_certificate /etc/letsencrypt/live/domainname/cert.pem;
ssl_certificate_key /etc/letsencrypt/live/domainname/privkey.pem;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
}