MYF

使用Let’s Encrypt为网站添加https

使用namecheap搞了好久才加上https,没想到使用Let’s Encrypt这么简单,记录一下

背景

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

准备工作

下载certbot

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

添加ssl

生成密钥

1
./certbot-auto certonly
  1. Place files in webroot directory(webroot)
  2. 输入域名,如py3.menyifan.com
  3. 输入网站根目录路径
1
2
3
4
5
6
7
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这个目录里,只有root用户可以访问

为Apache设置ssl

  1. /usr/local/apache/conf/httpd.conf 中开启 Include conf/extra/httpd-ssl.conf ,也就是将前面的 “#” 去掉。
  2. mv /usr/local/apache/conf/extra/httpd-ssl.conf /usr/local/apache/conf/extra/httpd-ssl.conf_bak # 备份自带的
  3. 编辑/usr/local/apache/conf/extra/httpd-ssl.conf,替换$yourweb.site.com$yourpathyourweb_site_com三者即可,Sample 内容如下:
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
Listen 443
SSLPassPhraseDialog builtin
SSLSessionCache "shmcb:/usr/local/apache/logs/ssl_scache(512000)"
SSLSessionCacheTimeout 300

<VirtualHost *:443>
DirectoryIndex index.php index.html index.htm
DocumentRoot /data/www/$yourpath/
ServerName $yourweb.site.com
ErrorLog "/usr/local/apache/logs/yourweb_site_com_error_log"
TransferLog "/usr/local/apache/logs/yourweb_site_com_access_log"
SSLEngine on
SSLProtocol All -SSLv2 -SSLv3
SSLHonorCipherOrder on
SSLCipherSuite ALL:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA
SSLCertificateFile /etc/letsencrypt/live/$yourweb.site.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/$yourweb.site.com/privkey.pem
CustomLog "/usr/local/apache/logs/yourweb_site_com_request_log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b \"%{Referer}i\" \"%{User-Agent}i\""
BrowserMatch "MSIE [2-5]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
<Directory /data/www/$yourpath/>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>

/etc/init.d/httpd restart 重启Apache

重定向

尝试了在Apache配置文件里加301重定向,觉得还是直接创建一个文件更简单,将下面的内容改为你需要的粘贴到/data/www/$yourpath/.htaccess路径下

1
2
3
4
5
6
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yoursite.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^www.yoursite.com $ [NC]
RewriteRule ^(.*)$ https://yoursite.com/$1 [L,R=301]

设置计划任务

因为整数的有效时间只有三个月,每次需要使用./certbot-auto renew来重新签发证书,所以我们干脆可以设置一个计划任务,让他每个月一号凌晨3:30分执行一次,感谢$STay$学弟建议使用强制命令

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

参考文章