天天看點

httpd 重定向

文章目录

      • httpd 重定向
        • 一、重定向
          • 1.1 格式:
          • 2.2 参数
          • 2.3 例:
            • 2.3.1 方法一
            • 2.3.2 不使用虚拟主机的方式
        • 二、HSTS:
          • HTTP Strict Transport Security
          • HSTS的作用 :
          • HSTS preload list
          • 实现HSTS示例:

httpd 重定向

一、重定向

1.1 格式:
Redirect [status] URL-path URL
2.2 参数

status状态:

  • Permanent: 返回永久重定向状态码 301
  • Temp:返回临时重定向状态码302. 此为默认值
2.3 例:

当访问 http://www.a.com 跳转到https://www.a.com

环境:实现https的访问(看一节)

2.3.1 方法一

通过虚拟主机的方式

<virtualhost *:80>
documentroot /data/asite
servername www.a.com
<Directory "/data/asite">
    Require all granted
 </Directory>
 redirect temp / https://www.a.com                                                            
 </virtualhost>
           

测试:

[[email protected] ~]# curl  -I  www.a.com
HTTP/1.1 302 Found
Date: Sat, 22 Feb 2020 18:32:57 GMT
Server: Apache
Location: https://www.a.com
Content-Type: text/html; charset=iso-8859-1

[[email protected] ~]# curl  -Lk  www.a.com
a  aa
           

2.3.2 不使用虚拟主机的方式

conf

DocumentRoot "/var/www/html"
redirect temp / https://www.a.com     
           

测试 ,发现报错了

[[email protected] ~]# curl www.a.com
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="https://www.a.com">here</a>.</p>
</body></html>
[[email protected] ~]# curl -Lk www.a.com
curl: (47) Maximum (50) redirects followed
           

不用 redirect , 换种方式,则可以解决

DocumentRoot "/var/www/html"

RewriteEngine on                                                                                                                           
RewriteRule ^(/.*)$  https://%{HTTP_HOST}$1 [redirect=302]
           

测试

[[email protected] ~]# curl -I www.a.com
HTTP/1.1 302 Found
Date: Sat, 22 Feb 2020 18:56:55 GMT
Server: Apache
Location: https://www.a.com/
Content-Type: text/html; charset=iso-8859-1

[[email protected] ~]# curl -Lk www.a.com
a  aa

           

二、HSTS:

HTTP Strict Transport Security
​ 服务器端配置支持HSTS后,会在给浏览器返回的HTTP首部中携带HSTS字段。 浏览器获取到该信息后,会将所有HTTP访问请求在内部做307跳转到HTTPS。 而无需任何网络过程
HSTS的作用 :

可以避免因为重定向的过程中被劫持

缺点:无法避免第一次请求的过程中被劫持。所以有了HSTS preload list

HSTS preload list

​ 是Chrome浏览器中的HSTS预载入列表,在该列表中的网站,使用Chrome浏 览器访问时,会自动转换成HTTPS。Firefox、Safari、Edge浏览器也会采用这 个列表

实现HSTS示例:

conf

vim /etc/httpd/conf/httpd.conf 
Header always set Strict-Transport-Security "max-age=31536000" RewriteEngine on 
RewriteEngine on                                                                                                                           
RewriteRule ^(/.*)$  https://%{HTTP_HOST}$1 [redirect=302]
           

验证

[[email protected] ~]# curl -I www.a.com
HTTP/1.1 302 Found
Date: Sat, 22 Feb 2020 19:32:47 GMT
Server: Apache
Strict-Transport-Security: max-age=31536000
Location: https://www.a.com/
Content-Type: text/html; charset=iso-8859-1
           

繼續閱讀