Nginx和letsencrypt

前言

之前使用caddy的,但是不知道为什么加了一条反代条目之后,用systemctl start caddy就一直启动失败,报错是无法获取证书,但是使用caddy -conf /etc/caddy/Caddyfile 启动是正常的。。。所以干脆自己申请证书,使用nginx了。

Let’s Encrypt申请免费SSL证书

安装Cerbot

我使用的是ubuntu18.04,安装命令如下:

1
2
3
4
5
sudo apt-get install software-properties-common
sudo add-apt-repository universe
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot

获取证书

  • 获取证书有两种方式,如果指定了web根目录,可以使用
1
certbot certonly --webroot -w /var/www/example -d example.com -d www.example.com
  • 不需要指定根目录的,可以使用(次方法必须停掉占用443端口的服务)
1
certbot certonly --standalone -d example.com -d www.example.com

好了之后,证书就在:/etc/letsencrypt/live/example.com目录下面了

更新证书

1
letsencrypt renew --agree-tos

Nginx

安装Nginx

1
sudo apt install nginx

配置Nginx

新建一个配置文件,这里我用来做v2ray反向代理的

1
vi /etc/nginx/conf.d/v2ray.conf

下面是配置内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server {
listen 443 ssl;
server_name example.com;

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; --路径里的域名要替换一下
ssl_certificate_key /etc/letsencrypt/live/lexample.com/privkey.pem; --路径里的域名要替换一下
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
error_page 497 https://$host$request_uri;

location / { -- 这里我反向代理了rocket.chat 服务
proxy_pass http://127.0.0.1:3000;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
}
}

保存之后,systemctl start|restart nginx 就好了。

参考资料:Let’s Encrypt 使用教程