Apache Http重定向到Https非常重要且关键,若没有对重定向进行配置,那么ssl的保护性将可以被绕过。
ubuntu16 apache2.2
已经配置好了SSL证书,已经实现了使用https访问站点(若没有实现,请参考该博文)
实现非常简单仅需3步
配置文件路径为 /etc/apache2/sites-available
80端口的配置文件名称为 000-default.conf
80端口修改内容为
在
关于修改方法有两个版本,建议使用版本二
版本一 (注意 www.xxxx.com、xxxx.com 中xxx要改成你的域名)
ServerName www.xxxx.com
ServerAlias xxxx.com
RewriteEngine On
RewriteRule ^/(.*?)$ https://www.xxxx.com/$1 [R]
版本二 (注意 www.xxxx.com、xxxx.com 中xxx要改成你的域名)
ServerName www.xxxx.com
ServerAlias xxxx.com
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://%{SERVER_NAME}$1 [L,R]
关于版本二命令解释
RewriteEngine On是开启rewrite功能
RewriteCond %{HTTPS} !=on 为不是https的时候执行下面的规则
^(.*) https://%{SERVER_NAME}$1 [L,R] 中 ^ 匹配行的开始
$1引用RewriteRule中的第一个正则(.*)代表的字符, %{SERVER_NAME}就是监听的网站域名,
[L]:结尾标识。停止重写操作,并不再应用其他重写规则。防止本条规则被后续规则影响
R 强制外部重定向
版本一与版本二的区别
1、版本一重定向规则都是使用硬编码,耦合性太强,建议使用版本二
2、版本二的重定向规则的正则表达式比版本一,加入了结尾表示 更加全面,也比较安全
3、我的版本二比其他晚上版本区别的地方是,原来的000-default.conf里面没有ServerName,若直接使用版本而,重启服务会失败
修改后效果
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
#ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
#加入内容
RewriteEngine on
ServerName www.xxxx.com
ServerAlias xxxx.com
RewriteEngine On
RewriteRule ^/(.*?)$ https://www.xxxx.com/$1 [R]
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
sudo a2enmod rewrite
sudo systemctl restart apache2
测试方法很简单,尝试使用http访问,注意地址是否会变成https