最近因为开发微信小程序,需要在服务端搭建https,在网上找了几篇配置SSL的博客,感觉都不是特别满意,感觉这一篇写的还挺好的。
1.查找apache的SSL模块
ubuntu下,apache的默认模块目录是/usr/lib/apache2/modules/
$ cd /usr/lib/apache2/modules/
$ ls
找到"mod_ssl.so"模块后,我们到apache的配置目录,默认是/etc/apache2
在该目录下面我们找到apache2.conf
$ cd /etc/apache2
$ ls
$ vi apache2.conf
2.增加mod_ssl.so依赖
在最后一行加上
LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so
3.HTTP配置访问
打开sites-enabled文件,打开000-default.conf文件,如果没有此文件新建一个。
并且修改内容如下所示
<VirtualHost *:80>
ServerName safe.example.com #(要绑定的域名)
Options FollowSymLinks
# 自动将80端口的访问,重定向到https的域名
Redirect permanent / https://safe.example.com
# 也可以使用IF-ELSE条件选择来禁止IP访问:
# <If "%{HTTP_HOST} == 'safe.example.com'">
# Redirect permanent / https://safe.example.com/
# </If>
# <Else>
# Order allow,deny
# Deny from all
# </Else>
# 详情参见: https://httpd.apache.org/docs/2.4/expr.html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
将上面的ServerName和Redirect permanent改成自己的域名即可
4.HTTPS访问控制
找到目录/etc/apache2,打开ports.conf文件
原内容:
Listen 80
<IfModule ssl_module>
Listen 443
</IfModule>
替换内容为
<IfModule ssl_module>
Listen 443
<VirtualHost _default_:443>
# 此处为网站根目录
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLEngine On
# 证书文件的路径(需要自己申请,或找IT部门的同事要)
SSLCertificateFile "./SSL_Cert/safe.example.com.cert"
# key文件的路径(需要自己申请,或找IT部门的同事要)
SSLCertificateKeyFile "./SSL_Cert/safe.example.com.key"
</VirtualHost>
</IfModule>
注:从腾讯云服务器上面免费申请的有三个文件,需要三个文件都加上
路径的话按照自己的实际情况来。
此处再提一下怎样去腾讯云申请免费的证书
登录腾讯云平台,在腾讯云的SSL证书管理服务模块,有一个申请证书,你选择那个有效期为1年的免费证书就行。然后下载下来,压缩包里面有个4个文件夹,分别是apache,tomcat和nginx以及IIS服务器软件的,选择对应的文件就行。
5.启用服务
$ apachectl configtest # 检查apache配置是否正确
$ sudo service apache2 reload # 检查配置正确后,重新加载配置
$ sudo a2enmod ssl # 启用SSL服务
$ sudo service apache2 restart #重启apache
禁用SSL服务是
$ sudo a2dismod ssl
6.完成
如果你配置正确,那么访问
- http://safe.example.com
- https://safe.example.com
- safe.example.com
都会重定向到 https://safe.example.com
以上资料感谢博客主依斯特的博客支持。