其实我早就就想设置HTTPS在我的nginx服务器上了。一直懒得弄,又拖拉,还好有一个五一小长假,花了小半天时间研究这个,遇到了许多问题,也都解决了。可是,当我弄好这玩意的时候发现,我的服务器被政府给墙了,这尼玛,让我一个党支部书记情何以堪。突然间就没有什么动力去搞“红色1+1”了呢……想起一个事儿,前两天我给两个发展对象准备转预备党员的材料,老师问我他们的情况我还一通夸奖,结果下午他们两个人都被校党课的老师拉了去组织谈话了,我的心情非常复杂。

环境

CentOS 7
nginx 1.8.1

生成密钥

使用秋水逸冰的LAMP一键安装包,设置均为默认

下载certbot

1
2
3
wget https://dl.eff.org/certbot-auto
chmod a+x certbot-auto
./certbot-auto

密钥设置

在根目录下执行

1
./certbot-auto certonly

  • Place files in webroot directory(webroot)
  • 输入域名,如beyondtech.club(这个的前提是你的域名已尽指向你的服务器,否则会出现错误)
  • 输入网站根目录路径

出现

IMPORTANT NOTES:

  • Congratulations! Your certificate and chain have been saved at
    /etc/letsencrypt/live/$yourdomain/fullchain.pem. Your cert will
    expire on 2016--. To obtain a new or tweaked version of this
    certificate in the future, simply run certbot-auto again. To
    non-interactively renew all of your certificates, run
    “certbot-auto renew”

代表密钥生成成功,放在/etc/letsencrypt/live/$yourdomain这个目录里。建议阅读该目录下的README。

配置Nginx

模块配置

我先是遇到了内存不足的报错,清理内存后还是不够,无奈升级服务器,又遇到了nginx: [emerg] the "ssl" parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:xxx报错.

查看

输入/usr/local/nginx/sbin/nginx -V
查看你nginx的安装的设置命令,如果没有--with-http_ssl_module的话,在最后会有nginx: [emerg] the "ssl" parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:XXX的报错。

重新编译安装

如果你的服务器上没有nginx的安装包的话,去官网下载一个。最好解压到/usr/local/src/目录下,然后进入nginx安装文件夹.根据上一步查看出的设置命令后加上必要的ssl_module模块,用./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_modul编译,成功后用make命令安装。

Nginx配置文件设置

修改/usr/local/nginx/conf/目录下的nginx.conf。
注意把beyondtech.club改成自己的域名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server {
listen 443 ssl;
# server_name localhost;
server_name beyondtech.club;
ssl_certificate /etc/letsencrypt/live/beyondtech.club/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/beyondtech.club/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/beyondtech.club/chain.pem;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
#ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root BeyondTech;
index index.html index.htm;
}
}

重启nginx即可用https访问。
TIP:可以在原来80端口的serve代码块中加上一句rewrite ^(.*) https://$server_name$1 permanent;可以将余名重定向到https
如果搞不清楚就看官方文档
推荐一个SSL配置文件生成器

防火墙

为了安全,最好开启防火墙,并且开放443端口。这些命令我之前的博文中都有写。
不能打开防火墙,不然的话服务器会拒绝其他人的访问……

1
2
3
4
systemctl stop firewalld.service #停止firewall
systemctl start firewalld.service #开启
systemctl disable firewalld.service #禁止firewall开机启动
firewall-cmd --state #查看默认防火墙状态(关闭后显示notrunning,开启后显示running)

当然没如果你会配置iptable的话那更好了。

自动化命令

因为这个密钥有效期只有90天,所以写自动执行的命令去定期更新。

1
2
crontab -e # 编辑计划任务
30 4 15 * * ~/certbot-auto renew --force-renewal # 加入计划任务

30 4 15 * *分别代表分钟,小时,日,月,星期几。我的就是每个月15号的4点30分执行这条命。

参考与福利

现在godady搞活动,一些.com和。club的域名只要7元一年,加上优惠码,我的beyondtech.club域名只花了5块多,赶紧去抢啊。

参考

门神
Cerbot官方文档
Nginx官方文档