1、开启SSL模块
$ a2enmod ssl
2、启用SSL站点
$ a2ensite default-ssl
3、加入监听端口
$ sudo vim /etc/apache2/ports.conf
编辑Apache端口配置,加入443端口 (HTTPS采用的443端口传输数据)
Listen 443
4、配置虚拟主机
编辑default-ssl文件,加入证书对应的主机头。
$ sudo vim /etc/apache2/sites-enabled/default-ssl.conf
ServerName extend.me
5、配置SSL证书
- 按如下配置:
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/ca.crt
SSLCertificateKeyFile /etc/apache2/ssl/server.key
- 重新启动Apache
$ sudo service apache2 restart
SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
编辑器打开.htaccess文件,写入如下规则:
RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{REQUEST_URI} !^/tz.php
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R]
解释:
%{SERVER_PORT} —— 访问端口
%{REQUEST_URI} —— 比如如果url是 http://localhost/tz.php,则是指 /tz.php
%{SERVER_NAME} —— 比如如果url是 http://localhost/tz.php,则是指 localhost
以上规则的意思是,如果访问的url的端口不是443,且访问页面不是tz.php,则应用RewriteRule这条规则。这样便实现了:访问了 http://localhost/index.php 或者 http://localhost/admin/index.php 等页面的时候会自动跳转到 https://localhost/index.php 或者 https://localhost/admin/index.php,但是访问 http://localhost/tz.php 的时候就不会做任何跳转,也就是说 http://localhost/tz.php 和 https://localhost/tz.php 两个地址都可以访问。